본문 바로가기
Programming Language/Python

[Python] 파이썬 웹 스크래핑 시, 유용한 BeautifulSoup4! 라이브러리 소개

by 뒹굴거리는프로도 2024. 1. 26.
반응형

 


 

BeautifulSoup는 html과 xml 파일로부터 데이터를 추출하는 유명한 파이썬 라이브러리입니다.

원하는 파일, 원하는 웹 링크의 내용을 탐색하고 싶다면 BeautifulSoup에서 제공하는 기능을 활용할 수 있습니다.

 

예를 통해 간단하게 확인해 봅시다.

 

아래 문서는 '이상한 나라의 앨리스' 이야기의 일부분을 포함하고 있는 html 입니다.

html_doc = """
<html><head><title>The Dormouse's story</title></head>

<p class="title"><b>The Dormouse's story</b></p>

<p class="story">Once upon a time there were three little sisters; and their names were
<a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>,
<a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
<a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;
and they lived at the bottom of a well.</p>

<p class="story">...</p>

 

이 html 파일을 beautifulSoup에 넣어주면, 아래와 같이 출력해 줍니다.

from bs4 import BeautifulSoup
soup = BeautifulSoup(html_doc)

print(soup.prettify())
# <html>
#  <head>
#   <title>
#    The Dormouse's story
#   </title>
#  </head>
#  <body>
#   <p class="title">
#    <b>
#     The Dormouse's story
#    </b>
#   </p>
#   <p class="story">
#    Once upon a time there were three little sisters; and their names were
#    <a class="sister" href="http://example.com/elsie" id="link1">
#     Elsie
#    </a>
#    ,
#    <a class="sister" href="http://example.com/lacie" id="link2">
#     Lacie
#    </a>
#    and
#    <a class="sister" href="http://example.com/tillie" id="link2">
#     Tillie
#    </a>
#    ; and they lived at the bottom of a well.
#   </p>
#   <p class="story">
#    ...
#   </p>
#  </body>
# </html>

 

soup 객체를 다음 방법처럼 활용하면요, html의 여러 요소들에 접근할 수 있습니다.

soup.title
# <title>The Dormouse's story</title>

soup.title.name
# u'title'

soup.title.string
# u'The Dormouse's story'

soup.title.parent.name
# u'head'

soup.p
# <p class="title"><b>The Dormouse's story</b></p>

soup.p['class']
# u'title'

soup.a
# <a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>

soup.find_all('a')
# [<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>,
#  <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>,
#  <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]

soup.find(id="link3")
# <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>

 

만약 html 문서에서 url만 모아 보고 싶다면, soup 객체를 통하여 모든 <a> 태그에서 url들을 추출할 수 있습니다.

for link in soup.find_all('a'):
    print(link.get('href'))
    
# http://example.com/elsie
# http://example.com/lacie
# http://example.com/tillie

 

또한 html에서 text만 추출할 수 있는데요, 아주 유용한 기능이지요?

print(soup.get_text())
# The Dormouse's story
#
# The Dormouse's story
#
# Once upon a time there were three little sisters; and their names were
# Elsie,
# Lacie and
# Tillie;
# and they lived at the bottom of a well.
#
# ...

 

현재 BeatifulSoup는 버전 4까지 릴리즈 되었다고 해요.

정리해 드린 예시 외에도 유용하게 쓰일 수 있는 여러 기능들을 제공하니 document를 확인해 보세요!

 


 

반응형