본문 바로가기

레퍼런스

웹스크래핑(크롤링)

예제 1.

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)

# 코딩 시작

# 웹스크래핑 할 부분 우클릭 > 검사 > console 창에 선택된 영역 부분 우클릭 > copy > copy selector로 가져오기
#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.number 노래 순위
#body-content > div.newest-list > div > table > tbody > tr:nth-child(1) > td.info > a.artist.ellipsis 가수

# select 로 리스트 불러오기
musics = soup.select('#body-content > div.newest-list > div > table > tbody > tr')
# print(musics)

# for 구문 이용하여 불러온 데이터 사용
for music in musics:
    a = music.select_one('td.info > a.title.ellipsis')
    if a is not None:
        title = a.text.strip()
        rank = music.select_one('td.number').text[0:2].strip()
        artist = music.select_one('td.info > a.artist.ellipsis').text

    print(rank, title, artist)

예제2.

 

import requests
from bs4 import BeautifulSoup

#DB 연결
from pymongo import MongoClient
client = MongoClient('mongodb+srv://test:sparta@cluster0.ibmct.mongodb.net/Cluster0?retryWrites=true&w=majority')
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'}
data = requests.get('https://movie.naver.com/movie/sdb/rank/rmovie.naver?sel=pnt&date=20210829',headers=headers)

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

# 코딩 시작

#old_content > table > tbody > tr:nth-child(2) > td.title > div > a 영화제목
#old_content > table > tbody > tr:nth-child(2) > td:nth-child(1) > img 영화순위
#old_content > table > tbody > tr:nth-child(2) > td.point 영화평점
movies = soup.select('#old_content > table > tbody > tr')
print(movies)

for movie in movies:
    a = movie.select_one('td.title > div > a')
    if a is not None:
        title = a.text
        star = movie.select_one('td.point').text
        rank = movie.select_one('td:nth-child(1) > img')['alt']
        #가져온 데이터를 딕셔너리형태로 저장
        doc = {
            'title':title,
            'rank':rank,
            'star':star
        }
        #DB에 데이터 저장
        db.movies.insert_one(doc)