지니뮤직 크롤링(스크래핑)하기

bird.j·2021년 2월 18일

web기본

목록 보기
12/19

지니뮤직 크롤링(스크래핑)하기

지니뮤직 페이지 -> 마우스 우클릭 -> 검사 -> copy selector

import requests
from bs4 import BeautifulSoup

from pymongo import MongoClient
client = MongoClient('localhost', 27017)
db = client.dbsparta

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'}
# 지니뮤직 url
data = requests.get('https://www.genie.co.kr/chart/top200?ditc=D&ymd=20200403&hh=23&rtm=N&pg=1',headers=headers)
# soup : html형식
soup = BeautifulSoup(data.text, 'html.parser')

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

for tr in trs:

    # tr이후부터('#'없음 주의), .strip()는 공백제거
    rank = tr.select_one('td.number').text[0:2].strip()
    title = tr.select_one('td.info > a.title.ellipsis').text.strip()
    name = tr.select_one('td.info > a.artist.ellipsis').text
    print(rank, title, name)

# DB에 저장
    doc = {
        'rank': rank,
        'title': title,
        'name': name
    }
    db.musics.insert_one(doc)

0개의 댓글