웹 스크래핑(Web Scraping)을 할 때, HTML을 파싱하여 원하는 데이터를 추출하는 것이 필수적입니다. Python에서는 다양한 HTML 파싱 라이브러리를 사용할 수 있으며, 이 글에서는 Beautiful Soup, lxml, html.parser를 비교하고 각각의 사용법을 소개하겠습니다.
from bs4 import BeautifulSoup
soup = BeautifulSoup('<html><body><h1>Hello</h1></body></html>', 'html.parser')
print(soup.h1.string) # Output: Hello
from lxml import etree
tree = etree.fromstring('<html><body><h1>Hello</h1></body></html>')
print(tree.find('./h1').text) # Output: Hello
from html.parser import HTMLParser
class MyParser(HTMLParser):
def handle_starttag(self, tag, attrs):
print("Start tag:", tag)
parser = MyParser()
parser.feed('<html><body><h1>Hello</h1></body></html>')
BeautifulSoup 객체는 HTML 문서를 파싱한 후 태그(Tag) 객체로 접근할 수 있습니다.
from bs4 import BeautifulSoup
soup = BeautifulSoup('<b class="boldest">Extremely bold</b>', 'html.parser')
tag = soup.b
type(tag) # <class 'bs4.element.Tag'>
prettify() 메서드를 사용하면 파싱된 HTML을 보기 좋게 정렬할 수 있습니다.
markup = '<a href="http://example.com/">I linked to <i>example.com</i></a>'
soup = BeautifulSoup(markup, 'html.parser')
print(soup.prettify())
soup.find('title') # <title>The Dormouse's story</title>
soup.find_all('title', limit=1) # [<title>The Dormouse's story</title>]
| 라이브러리 | 장점 | 단점 |
|---|---|---|
| Beautiful Soup | 사용이 쉬움, 깨진 HTML도 처리 가능 | 상대적으로 속도가 느림 |
| lxml | 매우 빠름, XPath 지원 | 별도 설치 필요, 문서화 부족 |
| html.parser | 기본 제공, 빠름 | 기능이 제한적 |
추천:
html.parser 사용이제 HTML 데이터를 파싱하고 원하는 정보를 추출하는 다양한 방법을 배웠습니다.