반응형
BeautifulSoup은 파이썬 라이브러리로, HTML 및 XML 문서에서 데이터를 추출하기 쉽게 만들어줍니다. 웹 스크래핑 작업에서 널리 사용되며, 셀레니움과 함께 사용하면 웹 페이지의 구조를 분석하고 필요한 정보를 추출하는 데 매우 유용합니다. BeautifulSoup은 HTML 파싱을 단순화하고, 탐색, 검색 및 수정 작업을 쉽게 수행할 수 있도록 도와줍니다.
BeautifulSoup의 주요 기능
- HTML 및 XML 파싱: BeautifulSoup은 다양한 파서(parser)를 지원하며, HTML 및 XML 문서를 파싱하여 파이썬 객체로 변환할 수 있습니다.
- 탐색 및 검색: BeautifulSoup은 태그, 속성, 텍스트 등을 기반으로 문서 내 요소를 쉽게 탐색하고 검색할 수 있는 기능을 제공합니다.
- 데이터 추출: BeautifulSoup을 사용하면 웹 페이지에서 필요한 데이터를 쉽게 추출할 수 있습니다.
BeautifulSoup 설치
BeautifulSoup을 사용하려면 먼저 설치해야 합니다. 또한, 파싱을 위해 lxml이나 html.parser 같은 파서도 함께 설치하는 것이 좋습니다.
pip install beautifulsoup4
pip install lxml
BeautifulSoup 기본 사용법
아래는 BeautifulSoup을 사용하여 HTML 문서를 파싱하고 데이터를 추출하는 기본적인 예제입니다.
from bs4 import BeautifulSoup
# 예제 HTML 문서
html_doc = """
<html>
<head>
<title>The Dormouse's story</title>
</head>
<body>
<h1>My First Heading</h1>
<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>
</body>
</html>
"""
# BeautifulSoup 객체 생성
soup = BeautifulSoup(html_doc, 'lxml')
# HTML 문서에서 title 태그 내용 추출
title = soup.title.string
print(title) # 출력: The Dormouse's story
# 첫 번째 p 태그의 class 속성 값 추출
first_p_class = soup.p['class']
print(first_p_class) # 출력: ['title']
# 모든 a 태그의 href 속성 값 추출
for a in soup.find_all('a'):
print(a['href'])
# 특정 id 값을 가진 요소 추출
link2 = soup.find(id='link2')
print(link2.string) # 출력: Lacie
반응형
'개발 > Python' 카테고리의 다른 글
[Python] Python이란? (2) | 2024.07.22 |
---|---|
[Python] BeautifulSoup을 이용한 간단한 멜론 인기차트 100위 가져오기. (0) | 2024.07.18 |
[Python] selenium을 이용한 인스타그램 좋아요 누르기. (0) | 2024.07.18 |
[Python] 셀레니움(Selenium)이란? (0) | 2024.07.18 |