본문 바로가기
Python

[Python Crawling] 파이썬 음악 순위 크롤링(스크랩핑)

by Jann 2022. 1. 28.
728x90

[Python Crawling] 파이썬 음악 순위 크롤링(스크랩핑)

 

* 지니뮤직의 랭킹, 제목, 가수를 크롤링하기 (20220128 기준 1-50위)

 

[Python Crawling] 파이썬 음악 순위 크롤링 코드

import requests
from bs4 import BeautifulSoup

from pymongo import MongoClient #db는 pymongo
client = MongoClient('localhost', 27017)
db = client.dbjann #dbjann 저장

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=D&ymd=20220128&hh=23&rtm=N&pg=1',headers=headers)

soup = BeautifulSoup(data.text, 'html.parser')

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()
        #.text[0:2] : 0에서 2까지 텍스트만 출력 , .strip() 통해서 공백 제거
    title = tr.select_one('td.info > a.title.ellipsis').text.strip()
    singer = tr.select_one('td.info > a.artist.ellipsis').text

    doc = {  # doc {} 딕셔너리 형태로 저장
        'rank': rank,
        'title': title,
        'singer': singer
    }
    
    db.musics.insert_one(doc)  # db - musics 에 딕셔너리 형태로 저장
    print(rank, title, singer)

 

- 뷰티풀숩과 파이몽고 활용

- db = client.dbjann #dbjann 저장

- select 선택자를 통해 공통 trs 먼저 받아오기

- rank, title, singer 순으로 공통 trs 이후 선택자 개별값을 for문으로 받아오기

- doc안에 딕셔너리 형태로 받아서 db - musics에 저장(db.names.insert_one)하고 출력하기

 

파이썬 음악 순위 크롤링 결과 

 

파이썬 뷰티풀 숩과 파이몽고를 활용해 영화순위, 음악순위 크롤링을 연달아 직접 해보며 select (copy selector) 선택자를 활용한 크롤링에 많이 익숙해졌다.

크롤링의 Key는 정해진 형식 안에 크롤링 하고자 하는 URL, 저장할 db 이름, 크롤링 할 항목 명 등의 부분만 바꾸어 주면 된다는 점!

파이몽고에 데이터를 저장하고 관리하는데 있어서도 db 저장, 수정 등도 insert_one, find_one, update_one 등의 명령어에 익숙해지면 원활하게 사용할 수 있는거 같다:)

select 선택자 활용한 크롤링 이외에 meta 태그를 활용한 크롤링 부분도 이어 정리할 예정!

728x90

댓글