[항해99 사전준비] 웹개발종합반 - 3주차 개발일지
2022. 2. 9. 14:04ㆍHanghae99
3주 차 목표
- 파이썬 문법 익히기.
- 원하는 페이지를 크롤링 하기.
- pymongo를 통해 mongoDB를 제어하기.
3주 차 실습
크롤링하기
(실행창에 순위, 노래 제목, 가수 이름 띄우기)
지니 월간 차트 URL
https://www.genie.co.kr/chart/top200?ditc=M&rtm=N&ymd=20210701
PyCharm - 파일 - 설정
+ 버튼 클릭하여 requests 와 bs4 패키지 설치
genie.py 파일 생성
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')
URL 주소 입력 부분에 위의 지니 월간차트 URL 넣기.
랭크 부분에 마우스 우클릭 후 검사 클릭.
랭크 부분 HTML 코드 마우스 우클릭 후 Copy - Copy selector 클릭. (복사된 상태)
코드 작성할 때 붙여 넣기 (붙여 넣고 작업하면 편하다.)
# body-content 부터 tr 까지는 공통된 부분이기 때문에 묶어서 sings에 저장.
sings = soup.select('#body-content > div.newest-list > div > table > tbody > tr')
# 반복문을 통해 제목과 순위, 가수이름의 text 만 뽑아오자.
for sing in sings:
title = sing.select_one('td.info > a.title.ellipsis').text
rank = sing.select_one('td.number').text[0:2]
artist = sing.select_one('td.info > a.artist.ellipsis').text
tmp = title.replace('19금','') # replace() 함수를 사용하여 19금 문자열을 공백으로 변경.
print(rank.strip() , tmp.strip(), artist.strip()) # 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')
#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(1) > td.info > a.title.ellipsis 제목
#body-content > div.newest-list > div > table > tbody > tr:nth-child(1) > td.info > a.artist.ellipsis 가수
sings = soup.select('#body-content > div.newest-list > div > table > tbody > tr')
for sing in sings:
title = sing.select_one('td.info > a.title.ellipsis').text
rank = sing.select_one('td.number').text[0:2]
artist = sing.select_one('td.info > a.artist.ellipsis').text
tmp = title.replace('19금','')
print(rank.strip() , tmp.strip(), artist.strip())
결과
728x90
'Hanghae99' 카테고리의 다른 글
[항해99 사전준비] 웹개발종합반 - 5주차 개발일지 (끝) (0) | 2022.02.16 |
---|---|
[항해99 사전준비] 웹개발종합반 - 4주차 개발일지 (0) | 2022.02.15 |
[항해99 사전준비] 웹개발 종합반 - 2주차 개발일지 (0) | 2022.02.06 |
[항해99 사전준비] 웹개발 종합반 - 1주차 개발일지 (0) | 2022.02.03 |