본문 바로가기

스파르타 내일배움캠프

3주차 과제

import requests # import하는거
from bs4 import BeautifulSoup
from pymongo import MongoClient #pymongo를 쓰겠습니다
client = MongoClient('localhost', 27017) # 내 컴퓨터에서 지금 돌아가고 있는 mongoDB에 접속할 겁니다.
db = client.dbsparta   # dbsparta라고 하는 DB 이름으로 접속할 겁니다. 없으면 자동으로 생성


headers = {'User-Agent' : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36'}
data = requests.get('https://www.genie.co.kr/chart/top200?ditc=M&rtm=N&ymd=20210701',headers=headers)

soup = BeautifulSoup(data.text, 'html.parser')

trs = soup.select('#body-content > div.newest-list > div > table > tbody > tr')
#body-content > div.newest-list > div > table > tbody > tr:nth-child(1) > td.number
#body-content > div.newest-list > div > table > tbody > tr:nth-child(1) > td.info > a.title.ellipsis
#body-content > div.newest-list > div > table > tbody > tr:nth-child(1) > td.info > a.artist.ellipsis

for tr in trs:
    title = tr.select_one('td.info > a.title.ellipsis').text.strip()
    if '19금' in title:
        title = "19금" + title.strip('19금').strip()
        # 19금 단어를 제거하고, 19금 단어를 추가한뒤 공백제거
    rank = tr.select_one('td.number').text[0:2].strip()
    artist = tr.select_one('td.info > a.artist.ellipsis').text
    print(rank,title,artist)