코딩과 결혼합니다

3주차 숙제 (웹스크래핑) 본문

2세/Python

3주차 숙제 (웹스크래핑)

코딩러버 2023. 5. 10. 16:43
728x90

웹개발 종합반 3주차 - 3주차 숙제 (웹스크래핑)

 

 

 

*지니뮤직의 1~50위 곡을 스크래핑 해보기.

 

1) 새로운 파일 만들기

 

 

 

2) 크롤링의 기본코드 복붙

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(URL, headers=headers)
soup = BeautifulSoup(data.text, 'html.parser')

 

 

 

3) URL 바꾸기

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

그다음 print(soup)으로 데이터가 잘 찍히는 확인

 

 

4) 검사

검사를 해봤을때 곡 하나 하나가 <tr> 태그 안에 있음을 확인할 수 있다.

곡이름은 #body-content > div.newest-list > div > table > tbody > tr:nth-child(1) > td.info > a.title.ellipsis

               여기서 앞부분은 가져왔으니 필요한 td.info > a.title.ellipsis 여기 부분만 써주면 되겠다.

 

 

 

5) 곡제목 가져오기

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
    print(title)

실행해 보면

이 난리로 나온다.

 

 

 

6) 앞 뒤 공백 자르기

print(title.strip())

그럴 때에는 .strip()

 

 

 

7) 랭크 추가

for tr in trs:
    title = tr.select_one('td.info > a.title.ellipsis').text
    rank = tr.select_one('td.number').text
    print(rank)

rank또한 copy selector로 가져와서 필요한 부분 빼고 지운 다음 한 번 실행해 본다.

그럼 또 이지경으로 나옴

 

 

 

8) 앞에 두 개 까지만 나오도록 하기(순위만 나오도록) + 공백 없애기

print(rank[0:2].strip())

 

 

 

9) title, rank 프린트

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()
    print(title,rank)

 

 

 

10) artist도 추가하기

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('a.artist.ellipsis').text
    print(rank,title,artist)

print되는 순서는 rank - title - artist

완성 🙌🙌🙌🙌

 

 

 

사실 혼자서는 못 하고 해설 영상 보면서 했다. 처음에는 해설 영상을 봐도 뭔말인지 잘 이해를 못 했는데

2번째 봤을때는 완벽 이해!  다음 번에는 끝까지 혼자 해봐야겠다.

'2세 > Python' 카테고리의 다른 글

Flask  (0) 2023.05.11
Python 기초 문법 - 리스트  (0) 2023.05.10
mongoDB  (0) 2023.05.10
웹스크래핑(크롤링)  (0) 2023.05.08
requests 라이브러리  (0) 2023.05.08