본문 바로가기
코딩

스파르타코딩클럽 웹개발 종합반(3주차)

by 瓜田李下(과전이하) 2022. 11. 3.

스파르타 웹개발 종합반 3주차 수업일지

 

3-15 숙제 설명 (지니뮤직 크롤링 하기)

★지니뮤직 사이트

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

☆지니뮤직사이트에서 순위 / 곡 제목 / 가수를 스크래핑 하면 됩니다. (결과모습)

 

※힌트

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

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

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



pythonprac폴더에 genie.py 파이썬 파일 만들어 주고 시작!

 

hello.py 파일에서 파랗게 지정한 부분(↓사진 참고) / soup부분 까지 복사해서 genie.py 파일에 붙여넣어주기.

 

 

▶숙제에서는 db를 하지 않을 거기 때문에 파랗게 지정한 3줄은 지워주기 (mongoDB 부분)

 

▶data줄에 들어가는 url에는 지니뮤직사이트 url로 변경해주기

 

▶마지막으로 print(soup)해줘서 실행해주면!

 

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')

 

print(soup)



▷결과 실행 창 모습

 

♣여기서 부터 자기가 해보기!!

 

<숙제 해설>

▶1,2 등 (차례로) 순위에 마우스 우클릭 -> 검사 -> 복사 -> select copy 해서

soup 줄 밑에 차례로 복붙해주기!!

 

※ 해석

#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

 

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

 

for tr in trs:

   rank = tr.select_one('td.number')

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

 

-for문으로 돌려주고 

프린트 할 때 

.text[0:2] 하게 되면 앞에서 두글자만 끊어 줍니다! 

 

▷전(.text[0:2])

▷후(.text[0:2])

 

.strip() 은 양옆 여백을 없애줌

▷후(.strip())

 

 

 text/strip 자리 rank줄로 이동시켜도 전과 동일 

 

for tr in trs:

   rank = tr.select_one('td.number').text[0:2].strip()



▶이번에는 제목에 마우스 우클릭 -> 검사 -> 복사 -> select copy 해서 복붙해주기



title = tr.select_one('')

 

따움표 사이에 ↓파랗게 지정한 부분 넣어줌

 

 

for tr in trs:

   rank = tr.select_one('td.number').text[0:2].strip()

   title = tr.select_one('td.info > a.title.ellipsis')

   print(title.text.strip())

 

->이동 text/strip

title = tr.select_one('td.info > a.title.ellipsis').text.strip()



 

▶가수도 같은 방식으로 해줌

-> artistst는 여백같은 게 없어서 .text만 해줘도 됨! 

 

▶최종

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

 

for tr in trs:

   rank = tr.select_one('td.number').text[0:2].strip()

   title = tr.select_one('td.info > a.title.ellipsis').text.strip()

   artist = tr.select_one('td.info > a.artist.ellipsis').text

   print(rank, title, artist)

 

 

▷결과 실행창 모습

  

숙제 완성! (전체 코드)