웹개발 종합반 3주차 - 숙제 : 지니뮤직 1~50위 곡 스크래핑
2022. 1. 3. 01:53ㆍ코딩공부/스파르타코딩클럽 - 웹개발종합반
3주차 끝 & 숙제 설명
지니뮤직의 1~50위 곡을 스크래핑 해보세요.
힌트 : 순위와 곡제목이 깔끔하게 나오지 않을 거예요. 옆에 여백이 있다던가, 다른 글씨도 나온다던가.. 파이썬 내장 함수인 strip()을 잘 연구해보세요! (파이썬 문자열 자르기, 파이썬 공백 제거 구글링)
import requests
from bs4 import BeautifulSoup
from pymongo import MongoClient # 파이몽고를쓴다
client = MongoClient('localhost', 27017) # 내 컴퓨터에서
db = client.dbsparta # 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&rtm=N&ymd=20220101',headers=headers)
soup = BeautifulSoup(data.text, 'html.parser')
#body-content > div.newest-list > div > table > tbody > tr:nth-child(1) > td.number
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()
# tr에서 하나만 찾아준다
rank = tr.select_one('td.number').text[0:2].strip()
# 파이썬 문자열 자르기 구글링, 글자가 두개니까 두개까지 잘라줬다
artist = tr.select_one('td.info > a.artist.ellipsis').text
print(rank, title, artist)