
제가 썼던 코드는 아래와 같아요.
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=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')
for tr in trs:
td = tr.select_one('td')
rank = td.select_one('td.number').text[0:2].strip()
title = td.select_one('td.info > a.title.ellipsis').text.strip()
artist = td.select_one('td.info > a.artist.ellipsis').text
print(rank, title, artist)
그런데 그렇게 하면 안나오더라구요. 아래와 같은 터미널 결과가 나오구요.
---(터미널)
guihy@DESKTOP-OABH4GQ MINGW64 ~/Desktop/Sparta/pythonprac
$ c:/Users/guihy/Desktop/Sparta/pythonprac/venv/Scripts/python.exe c:/Users/guihy/Desktop/Sparta/pythonprac/genie.py
Traceback (most recent call last):
File "c:/Users/guihy/Desktop/Sparta/pythonprac/genie.py", line 12, in <module>
rank = td.select_one('td.number').text[0:2].strip()
AttributeError: 'NoneType' object has no attribute 'text'
(venv)
guihy@DESKTOP-OABH4GQ MINGW64 ~/Desktop/Sparta/pythonprac
$
---
왜 일까요?
td 줄이 하나 더 있기 때문인 것 같은데요, 제가 이걸 썼던 이유는. tr 자료들 중에서 td 태그?를 달고 있는 것들만 먼저 추리고 난 다음에 title, rank, artist로 좁히고 싶기 때문이었어요.
title, rank, artist를 tr에서 바로 뽑아도 되지만, tr에서 td를 먼저 뽑고, td에서 title, rank, artist를 뽑아도 (비효율적이긴 하지만) 결과가 동일하게 나와야 하는 것 아닌가요?
