1) 출력 할 때는 print(rank, title, artist) 사용
2) 앞에서 두 글자만 끊기! text[0:2] 를 사용하기
3) 순위와 곡제목이 깔끔하게 나오지 않을 거다. 옆에 여백이 있다던가, 다른 글씨도 나온다던가.. 파이썬 내장 함수인 strip() 구글링 해보기
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')
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].rstrip()
title = song.select_one('td.info > a.title.ellipsis').text.lstrip()
artist = song.select_one('td.info > a.artist.ellipsis').text
if "19금" in title:
print(rank, title.strip("19금").lstrip(), artist)
else:
print(rank, title, artist)
❗️여기까지 해줬는데 노래 중 Justin Bieber에 Peaches가 앞에 "19금" 단어가 붙어서 제거해 줘야 한다.
이거 하나만 그런 거라서 text[]로 해보자니 안 될 것 같아서 if 문을 써봤다. title 내에 "19금" 글자가 있으면 제거 하고 공백을 조정하라는...일단 요기까지 내가 해봤는데 잘 된다.
과연 숙제 답안 코드로 올라온 것과 차이가 얼마나 날까?
✔️ 3주차 숙제 답안 코드
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:
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)
이때는 peaches가 없었나; 별 다른 내용이 없네
곡 순위 리스트 중에 제일 좋아하는 노래로 머리를 쓴 게 아이러니🫠
파이썬 패키지를 통한 크롤링과 mongoDB 연결을 배웠다. 1~2주차가 프론트엔드라고 하면 3주차는 백엔드인건가? 구분이 맞나? 암튼 4주차부터 2개가 합쳐진다는데 어떻게 연결하고 진행되는지 궁금하다!
암튼 여기까지는 할만했음😙