처음부터 차근차근

beautifulsoup 사용법 본문

Language/Python

beautifulsoup 사용법

HangJu_95 2023. 5. 4. 20:12
728x90

웹스크래핑(크롤링)은 bs4를 사용하여 많이 진행된다.

requests와 bs4를 사용하여 크롤링을 진행하며, 이때 원하는 데이터를 가져올 수 있다.

 

먼저 내가 가져오고 싶은 데이터에 대해 알아야 한다.

원하는 URL에 들어간 뒤, 원하는 데이터에 왼쪽 클릭 > 검사를 클릭한다.

 

이후 확인 시 내가 원하는 데이터의 HTML을 볼 수 있다.

내가 원하는 항목에 Copy > copy selector를 하면 원하는 항목에 대한 주소를 알 수 있다.

ex) #mainContent > div > div.box_ranking > ol > li:nth-child(1) > div > div.thumb_cont > strong > a

 

크롤링 기본 세팅은 이렇게 동작한다.

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(URL, headers=headers)
soup = BeautifulSoup(data.text, 'html.parser')

원하는 영화 제목을 가져와보자.

title = soup.select_one("#mainContent > div > div.box_ranking > ol > li:nth-child(1) > div > div.thumb_cont > strong > a").text
print(title)

가져온 데이터는 Html의 뼈대이기 때문에 .text()를 사용하여 문자값만 꺼내준다.

 

다른 사용방법으로는

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

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

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

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

예시로 순위, 제목, 별점을 웹스크래핑해보자.

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(URL,headers=headers)
soup = BeautifulSoup(data.text, 'html.parser')

video_list = soup.select("#mainContent > div > div.box_ranking > ol > li")
for v in video_list:
  # print(v)
  rank = v.select_one(".rank_num").text
  title = v.select_one(".tit_item").text.strip("\n")
  rate = v.select_one(".txt_grade").text
  print(rank, title, rate)

 

추가적인 사용 방법은 bs4 공식 docu를 확인할 수 있다.

https://www.crummy.com/software/BeautifulSoup/bs4/doc/

 

Beautiful Soup Documentation — Beautiful Soup 4.12.0 documentation

Beautiful Soup Documentation Beautiful Soup is a Python library for pulling data out of HTML and XML files. It works with your favorite parser to provide idiomatic ways of navigating, searching, and modifying the parse tree. It commonly saves programmers h

www.crummy.com

 

'Language > Python' 카테고리의 다른 글

requests 라이브러리  (0) 2023.05.04
Python 가상 환경 설치  (0) 2023.05.04
Python Git bash 설치  (0) 2023.05.04