🔖지니뮤직의 1~50위 곡을 스크래핑 해보기
🔎 지니뮤직 사이트
https://www.genie.co.kr/chart/top200?ditc=M&rtm=N&ymd=20210701
지니차트>월간 - 지니
AI기반 감성 음악 추천
www.genie.co.kr
🔎 앞 두 글자만 추출
0, 1 인덱스 추출
text[0:2]
🔎 깔끔하게 추출하기
여백 제거
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')
# rank
#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(2) > td.number
# title
#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(2) > td.info > a.title.ellipsis
# artist
#body-content > div.newest-list > div > table > tbody > tr:nth-child(1) > td.info > a.artist.ellipsis
#body-content > div.newest-list > div > table > tbody > tr:nth-child(2) > td.info > a.artist.ellipsis
songs = soup.select('#body-content > div.newest-list > div > table > tbody > tr')
for song in songs:
a = song.select_one('td.number')
if a is not None:
rank = a.text[0:2].strip()
title = song.select_one('td.info > a.title.ellipsis').text.strip()
artist = song.select_one('td.info > a.artist.ellipsis').text.strip()
print(rank, title, artist)
☀️ 느낀점
songs = soup.select('#body-content > div.newest-list > div > table > tbody')
처음에 songs 추출할때, 요렇게 적었더니 랭킹 첫번째 값만 가져와서 당황했었다. 다시 html코드를 상세히 보고 >tr 추가해주니 원하는 대로 랭킹 순으로 프린트됐다.
해설 영상을 보니 출력결과 None이 없어 is not Null 문법을 사용하지 않았다.
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('td.info > a.title.ellipsis').text.strip()
artist = song.select_one('td.info > a.artist.ellipsis').text.strip()
print(rank, title, artist)
꼭 필요 없는 문법은 굳이 사용하지 않아도 되는데, 너무 예전에 연습했던 코드를 토대로 하니 불필요한 코드도 작성해렸다. 코드 작성할 때 한줄 한줄 출력을 보고 이 코드가 필요한지? 생각해보고 코드를 작성하는 습관을 길러야겠다.
'풀스택 개발일지' 카테고리의 다른 글
[웹개발 종합반 4주차] 프로젝트, 화성땅 공동구매 (0) | 2022.10.24 |
---|---|
[웹개발 종합반 4주차] 서버 만들기 (0) | 2022.10.24 |
[웹개발 종합반 3주차] DB, mongoDB (0) | 2022.10.23 |
[웹개발 종합반 3주차] 웹스크래핑(크롤링) (0) | 2022.10.21 |
[웹개발 종합반 3주차] Python, 크롤링, mongoDB (2) | 2022.10.21 |
댓글