반응형
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를 확인해 보세요!
반응형
'Programming Language > Python' 카테고리의 다른 글
[Python] 튜플(tuple), 요소를 바꿀 수 없는 순서 있는 시퀀스 (0) | 2024.02.15 |
---|---|
[Python] 2차원 배열 모든 요소에서 첫 번째 열을 선택하고 싶을 때는? [:,0] 사용하기 (0) | 2024.02.13 |
[Python] 파이썬 리스트 안에 for문 사용하는 형식, list comprehension (0) | 2024.01.11 |
[Python] 파이썬 딕셔너리에 key 존재 여부 확인 시, in 키워드 / get() 사용하기 (1) | 2024.01.11 |
[Python] 파이썬 문자열 정렬 시 sort()에서 사용하는 key 인자 (0) | 2024.01.05 |