항해99

[3주차] [#12] 3주차 끝 & 숙제 설명

Heoky 2022. 10. 14. 22:04
지니뮤직의 1~50위 곡을 스크래핑 해보세요.

 

지니뮤직 사이트

https://www.genie.co.kr/chart/top200?ditc=M&rtm=N&ymd=20210701

 

Q. 이렇게 되면 완성

힌트:

0) 출력 할 때는 print(rank, title, artist) 하면 됩니다!

1) 앞에서 두 글자만 끊기! text[0:2] 를 써보세요!

2) 순위와 곡제목이 깔끔하게 나오지 않을 거예요. 옆에 여백이 있다던가,
다른 글씨도 나온다던가.. 파이썬 내장 함수인 strip()을 잘 연구해보세요!

 



완성코드

import requests
from bs4 import BeautifulSoup

headers_url = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/106.0.0.0 Safari/537.36'
headers = {'User-Agent': headers_url}

# 크롤링 하려는 사이트의 주소
url = 'https://www.genie.co.kr/chart/top200?ditc=M&rtm=N&ymd=20210701'
data = requests.get(url, headers=headers)

soup = BeautifulSoup(data.text, 'html.parser')

# strip()
# 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(15) > td.info > a.title.ellipsis / 제목
# body-content > div.newest-list > div > table > tbody > tr:nth-child(15) > td.info > a.title.ellipsis > span
# body-content > div.newest-list > div > table > tbody > tr:nth-child(1) > td.info > a.artist.ellipsis / 가수

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

for music in musics:
    rank = music.select_one('td.number').text[0:2].strip()
    # music.select_one('td.info > a.title.ellipsis > span').decompose()
    title = music.select_one('td.info > a.title').text.strip()
    artist = music.select_one('td.info > a.artist.ellipsis').text
    print(rank, title, artist)

결과