파이썬 크롤링을 간단하게 진행해보는 방법을 알아보자.
해당 진행은 파이썬 개발툴인 Pycharm에서 진행하였고, 먼저 파일-설정-Python인터프리터에서 beautifulsoup4
패키지를 설치하여 진행하였다.
해당 패키지를 설치 후 진행 한 크롤링 사이트는 지니뮤직의 순위 페이지를 크롤링 해보았다. 먼저 크롤링 주소는
https://www.genie.co.kr/chart/top200?ditc=M&rtm=N&ymd=20210701
이고, 주소를 보면 20210701일 차트이다.
해당사이트를 들어간 후 내가 원하는 크롤링 결과물은
이고 내용은 순위, 제목, 가수인데 html의 구조를 잠시 확인하기 위해 사이트에서 순위에 마우스 오버 후 검사를 클릭한다.(크롬에서 진행함)
해당페이지에서 우클릭- 검사를 하면 위와 같이 해당 html태그가 선택되는데 , 우클릭-copy-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(1) > td.info > a.title.ellipsis
#body-content > div.newest-list > div > table > tbody > tr:nth-child(1) > td.info > a.artist.ellipsis
세개의 태그를 보면 nth-child(1)이 첫번째 순위인 '바라만 본다'이고 2번째 순위는 nth-child(2)로 되는 것을 알수있으므로, 공통 되는 코드인 tr까지 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')
#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 --가수
songs = soup.select('#body-content > div.newest-list > div > table > tbody > tr')
for song in songs:
a = song.select_one('td.number')
b = song.select_one('td.info > a.title.ellipsis')
c = song.select_one('td.info > a.artist.ellipsis')
rank = a.text[0:2].strip()#하강 상승 잘라야됨 1등부터 10등까지 공백빼야됨
title = b.text.strip() #앞뒤공백빼기위한 strip()
artist = c.text.strip()
print(rank,title,artist)
결과 코드인데, rank와 title,artist라는 변수에 담아서 반복문으로 순위를 출력하였고, 앞뒤 공백이 있는 부분은 strip이라는 파이썬 자체 문자열 처리 함수를 이용하여 제거하였다.
반응형
'Study > Python&Flask' 카테고리의 다른 글
MongoDB 전체검색,조건한개검색, 조건두개검색 (0) | 2022.06.23 |
---|---|
파이썬 플라스크 서버 기동(Pycharm) (0) | 2022.06.04 |