BeautifulSoup

怎么使用BeautifulSoup解析HTML文档

小亿
87
2024-05-14 10:53:11
栏目: 编程语言

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

  1. 导入BeautifulSoup库:
from bs4 import BeautifulSoup
  1. 创建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')
  1. 使用BeautifulSoup对象查找和提取需要的信息:
# 获取文档标题
title = soup.title
print(title.text)

# 获取第一个段落
paragraph = soup.p
print(paragraph.text)
  1. 使用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的功能。

0
看了该问题的人还看了