강의/웹개발 종합반

웹개발 종합반 3주차 숙제 - 지니 뮤직 크롤링하기

MotherCarGasoline 2022. 4. 12. 08:26

답안코드

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)

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

 


 

 

1. 크롤링 필요한 기본 코드,url 붙여넣기

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)

 

2. 지니뮤직 사이트 검사 > copy selector 가져오기

 

3. copy selector 코드 같은 부분 잘라내기

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

nth-child(1)..(2) 는 각 부여된 번호로 하나만 가져올 수 없다. 다 가져올 수 있는건

#body-content > div.newest-list > div > table > tbody > tr

 

4. for문을 돌려 rank,title,artist를 가져옴

 

.text 문자를 가져옴  + [0:2]는 첫 문자부터 3 번째 문자 까지 가져옴

.strip() 공백 제거

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)

 

 

mongoDB 연결 해결을 아직 못함

4월 경 3주차 FAQ에 있는 몽고db certifi 패키지 설치로 해결