[python] beautifulsoup4 Web Scraping, 웹 스크래핑

이주희·2023년 1월 21일
0

BackEnd

목록 보기
11/14

beautifulsoup4

HTML 구조를 파악하는 데 도움을 주는 패키지이다.

beautifulsoup 메서드

1) select()
조건을 만족하는 모든 요소를 리스트에 담아 반환한다.

2) select_one()
조건에 만족하는 요소 중 가장 먼저 나오는 요소를 반환한다.

# 선택자를 사용하는 방법 (copy selector)
soup.select('태그명')
soup.select('.클래스명')
soup.select('#아이디명')

soup.select('상위태그명 > 하위태그명 > 하위태그명')
soup.select('상위태그명.클래스명 > 하위태그명.클래스명')

# 태그와 속성값으로 찾는 방법
soup.select('태그명[속성="값"]')

# 한 개만 가져오고 싶은 경우
soup.select_one('위와 동일')

selector 가져오는 방법

개발자 도구에서 원하는 요소를 찾고 'Copy' > 'Copy selector'로 복사하면 해당 요소의 선택자를 가져올 수 있다.

#old_content > table > tbody > tr:nth-child(2)

설치하기

pip install beautifulsoup4

사용 방법

1. requests 패키지를 이용해 html 파일을 받아온다.

import requests

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.nhn?sel=pnt&date=20200303', headers=headers)

2. beautifulsoup4 패키지를 이용해 파싱 용이한 html로 변환한다.

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

3. soup.select를 이용해 원하는 부분만 추출한다.

movies = soup.select('#old_content > table > tbody > tr')

전체 코드

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://movie.naver.com/movie/sdb/rank/rmovie.nhn?sel=pnt&date=20200303', headers=headers)

soup = BeautifulSoup(data.text, 'html.parser')
movies = soup.select('#old_content > table > tbody > tr')
for movie in movies:
    a_tag = movie.select_one('td.title > div > a')
    point = movie.select_one('td.point')
    rank = movie.select_one('img')
    if rank is not None:
        print(rank['alt'], a_tag.text, point.text)
profile
🍓e-juhee.tistory.com 👈🏻 이사중

0개의 댓글