210419-TIL

김예지·2021년 4월 19일
0
  • 3주차 숙제 : 지니 뮤직에서 탑 50의 순위, 제목, 가수를 크롤링해오기
import requests
from bs4 import BeautifulSoup
from pymongo import MongoClient
client = MongoClient('localhost', 27017)
db = client.dbsparta

# URL을 읽어서 HTML를 받아오고,
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)

# HTML을 BeautifulSoup이라는 라이브러리를 활용해 검색하기 용이한 상태로 만듦
soup = BeautifulSoup(data.text, 'html.parser')

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

songs = soup.select('#body-content > div.newest-list > div > table > tbody > tr')

for song in songs:
    title = song.select_one('td.info > a.title.ellipsis').text.strip()
    singer = song.select_one('td.info > a.artist.ellipsis').text
    rank = song.select_one('td.number').text.split(' ')[0].strip()
    print(rank, title, singer)

첫 시도에는 실패했다. 마음이 급한 나머지 title, singer, rank를 한개씩 다 출력하려고 했고, 그 결과 에러페이지만 죽죽 나와버렸다.

진정한 후에, 일단 내가 원하는 데이터가 어디에 있는지부터 테스트해보았다. tr까지 크롤링 한 데이터를 songs에 넣은 후, for문을 통해 내가 원하는 데이터가 잘 출력되었는지 확인하였다.

뭐든 차근차근 하는게 중요하다. 한줄씩 잘 확인한 후에 넣으니 바로바로 잘 되었다.

profile
새싹

0개의 댓글