Bootstrap

python导入BeautifulSoup之后,该模块中常用参数的使用方法

BeautifulSoup 是一个用于解析 HTML 和 XML 文档的 Python 库,它依赖于解析器来解析文档,并提供了用于提取数据的简单方法。由于 BeautifulSoup 的参数和方法非常多,我将介绍一些常用的。

首先,确保你已经安装了 beautifulsoup4lxml(或 html.parser,但 lxml 更快):

pip install beautifulsoup4 lxml

基本用法

from bs4 import BeautifulSoup

# 假设我们有以下 HTML 内容
html_doc = """
<html>
<head>
    <title>我的网页</title>
</head>
<body>
    <p class="title"><b>页面标题</b></p>
    <p class="story">这里有很多文字,包括一些<a href="http://example.com/elsie" class="sister" id="link1">链接</a>,
    和一些<a href="http://example.com/lacie" class="sister" id="link2">其他链接</a>。</p>
</body>
</html>
"""

# 使用 BeautifulSoup 解析这段 HTML
soup = BeautifulSoup(html_doc, 'lxml')

# 打印 title 标签的内容
print(soup.title.string)  # 输出:我的网页

# 找到所有的 <a> 标签
for link in soup.find_all('a'):
    # 打印链接的文本和 URL
    print(link.get('href'), link.text)

常用方法

  • find_all(name, attrs, recursive, text, **kwargs)
    • 查找当前 tag 的所有 tag 子节点,并判断是否符合过滤器的条件。
# 查找所有的 <p> 标签
for p in soup.find_all('p'):
    print(p.text)
  • find(name, attrs, recursive, text, **kwargs)
    • 查找符合条件的第一个 tag。
# 查找第一个 <a> 标签
link = soup.find('a')
print(link.get('href'), link.text)
  • get_text()
    • 获取当前 tag 和所有子孙 tag 的文本内容。
# 获取 body 标签的文本内容
print(soup.body.get_text())
  • attrs
    • 获取 tag 的属性字典。
# 获取第一个 <a> 标签的属性
print(soup.find('a').attrs)

修改解析树

# 修改第一个 <a> 标签的文本
soup.find('a').string = "新链接"
print(soup.find('a'))

# 添加一个新的 <p> 标签
new_tag = soup.new_tag('p', **{'class': 'new'})
new_tag.string = "这是一个新标签"
soup.body.append(new_tag)
print(soup.body)

格式化输出

# 格式化输出修改后的 HTML
print(soup.prettify())

这只是 BeautifulSoup 库的一部分功能。更多信息和高级用法,如编码自动处理、格式化器、解析器之间的差异等,可以在 BeautifulSoup 官方文档 中找到。

;