숙제로 제출한 답안 코드
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')
#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
songs = soup.select('#body-content > div.newest-list > div > table > tbody > tr')
for song in songs :
rank = song.select_one('td.number').text[0:2].strip()
title = song.select_one('a.title.ellipsis').text.strip()
artist = song.select_one('a.artist.ellipsis').text
print(rank, title, artist)
해설 영상과 강의 자료로 확인하니 답안이 틀리진 않았습니다만, 직접 스크래핑 해서 출력 해보니 실시간 기준으로는 15위에 19금 노래가 들어가 있어요.
이것 때문에 title에 '19금' 이라는 span 으로 묶인 css class 가 있는데 위 숙제 코드로 출력 시 19금 + 공백 이 지워지질 않더라구요. strip()을 활용한 함수로는 lstrip, rstrip 모두 써봤지만 적용되지 않는 듯 했습니다. 혹시 이런 경우도 필요없는 text와 공백을 지우고 출력할 수 있는 방법이 있을까요?