您的位置:宽带测速网 > 编程知识 > 怎么使用BeautifulSoup解析HTML文档

怎么使用BeautifulSoup解析HTML文档

2025-07-04 09:35来源:互联网 [ ]

使用BeautifulSoup解析HTML文档的基本步骤如下:

    导入BeautifulSoup库:
from bs4 import BeautifulSoup
    创建BeautifulSoup对象并传入HTML文档和解析器:
html_doc = """<html><head><title>Example HTML Document</title></head><body><p>This is an example paragraph.</p></body></html>"""soup = BeautifulSoup(html_doc, 'html.parser')
    使用BeautifulSoup对象查找和提取需要的信息:
# 获取文档标题title = soup.titleprint(title.text)# 获取第一个段落paragraph = soup.pprint(paragraph.text)
    使用BeautifulSoup对象查找特定标签或属性的内容:
# 查找所有的段落标签paragraphs = soup.find_all('p')for p in paragraphs:print(p.text)# 查找包含特定class属性的标签div = soup.find('div', class_='example_class')print(div.text)

以上是使用BeautifulSoup解析HTML文档的基本方法,可以根据具体的需求和HTML文档结构来进一步应用BeautifulSoup的功能。