<내가 쓴 코드>
import requests
from bs4 import BeautifulSoup
from pymongo import MongoClient
client = MongoClient('localhost', 27017)
db = client.dbsparta
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=D&ymd=20200403&hh=23&rtm=N&pg=1',headers=headers)
soup = BeautifulSoup(data.text, 'html.parser')
trs = soup.select('#body-content > div.newest-list > div > table > tbody > tr')
for tr in trs:
a_tag = tr.select_one('td.info > a.title.ellipsis')
if a_tag is not None:
title = a_tag.text.strip()
rank = tr.select_one('td.number')
rank_num = rank.text.split()[0]
singer = tr.select_one('td.info > a.artist.ellipsis').text
print(rank_num, title, singer)
<답안>
import requests
from bs4 import BeautifulSoup
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=D&ymd=20200403&hh=23&rtm=N&pg=1',headers=headers)
soup = BeautifulSoup(data.text, 'html.parser')
trs = soup.select('#body-content > div.newest-list > div > table > tbody > tr')
for tr in trs:
title = tr.select_one('td.info > a.title.ellipsis').text.strip()
rank = tr.select_one('td.number').text[0:2].strip()
artist = tr.select_one('td.info > a.artist.ellipsis').text
print(rank, title, artist)
마치며
역시 내가 쓴 코드가 더 길고 지저분한 느낌이다.
그래도 답안과 다른 방법으로 같은 결과를 낸 건 뿌듯한 일이다.
rank = tr.select_one('td.number').text[0:2].strip()
이 코드를 생각해내지 못해서
rank_num = rank.text.split()[0]
이 코드로 순위를 가져왔다.