使用 BeautifulSoup 解析HTML内容+ 遍历搜索

本文介绍了BeautifulSoup在Python中处理HTML和XML的重要概念,包括标签、属性、NavigableString、BeautifulSoup对象、遍历方法(如find(),find_all(),children和descendants)以及CSS选择器的使用。
摘要由CSDN通过智能技术生成

Beautiful Soup 是 Python 中一个非常流行的 HTML/XML 解析库,它提供了一些重要的概念和方法来帮助我们对 HTML/XML 进行解析和处理。下面是一些 Beautiful Soup 中的重要概念:

  1. 标签(Tag):在 HTML/XML 中,标签用于定义文档的结构和内容。Beautiful Soup 可以通过搜索和遍历文档中的标签来获取其内容和属性。

  2. 属性(Attribute):HTML/XML 标签可以包含一些属性,如 classidhref 等。Beautiful Soup 可以通过搜索和遍历文档中的属性来获取其值。

  3. NavigableString:表示 Beautiful Soup 所解析的 HTML/XML 文档中的字符串。NavigableString 对象通常是 HTML/XML 标签中的文本内容。

  4. BeautifulSoup 对象:表示整个 HTML/XML 文档,在 Beautiful Soup 中创建该对象后,我们可以通过它来访问文档的各个部分,包括文档中的标签、字符串等。

  5. 遍历和搜索方法:Beautiful Soup 提供了多种方法来搜索和遍历 HTML/XML 文档中的标签和属性。比如 find()find_all() 方法可以用来搜索特定的标签或属性,childrendescendants 属性可以用来遍历文档中的标签等。

  6. CSS 选择器:基于 CSS 样式表语法的一种方式,用于在 HTML/XML 文档中选择特定的标签和属性。Beautiful Soup 支持使用 CSS 选择器来搜索和遍历文档中的元素。

children 属性用于遍历当前标签的直接子标签,返回一个迭代器

from bs4 import BeautifulSoup

html_doc = """
<html>
<head>
<title>Example Page</title>
</head>
<body>
<p>This is the first paragraph.</p>
<p class="important">This is the second paragraph.</p>
<p id="third">This is the third paragraph.</p>
</body>
</html>
"""
children 属性用于遍历当前标签的直接子标签,返回一个迭代器
soup = BeautifulSoup(html_doc, 'html.parser')
body_tag = soup.body
for child in body_tag.children:
    print(child)

parents遍历并打印当前标签的所有父节点

from bs4 import BeautifulSoup

# 假设有如下HTML内容
html_content = '''
<html>
<head>
<title>Example</title>
</head>
<body>
<div>
<p>This is a paragraph.</p>
<a href="#">This is a link.</a>
</div>
</body>
</html>
'''

# 使用 BeautifulSoup 解析HTML内容
soup = BeautifulSoup(html_content, 'html.parser')

# 选择一个标签,这里选择 <a> 标签
tag = soup.a

# parents遍历并打印当前标签的所有父节点
for parent in tag.parents:
    print(parent.name)

 descendants 属性用于遍历当前标签的所有子孙标签,返回一个迭代器。

from bs4 import BeautifulSoup
html_doc = """
<html>
<head>
<title>Example Page</title>
</head>
<body>
<p>This is the first paragraph.</p>
<div class="container">
    <p class="important">This is the second paragraph.</p>
    <ul>
        <li>Item 1</li>
        <li>Item 2</li>
    </ul>
</div>
<p id="third">This is the third paragraph.</p>
</body>
</html>
"""
descendants 属性用于遍历当前标签的所有子孙标签,返回一个迭代器。
与 children 属性不同的是,descendants 属性会递归遍历当前标签的所有子孙标签,包括嵌套的标签。
soup = BeautifulSoup(html_doc, 'html.parser')
for tag in soup.descendants:
    print(tag)

使用 select() 方法来执行 CSS 选择器查询

from bs4 import BeautifulSoup

html_doc = """
<html>
<body>
<a href="https://www.example.com">Link 1</a>
<a href="https://www.google.com">Link 2</a>
<a href="https://www.github.com">Link 3</a>
</body>
</html>
"""
# 在 Beautiful Soup 中,可以使用 select() 方法来执行 CSS 选择器查询
# 使用 CSS 选择器可以极大地简化我们对文档元素的定位和处理过程
# 选择元素标签名:soup.select('p')  # 返回所有 <p> 元素对象
# 选择类名为 class-name 的元素:soup.select('.class-name')  # 返回所有具有 class 为 "class-name" 的元素对象
# 选择 id 为 id-name 的元素:soup.select('#id-name')  # 返回具有 id 为 "id-name" 的元素对象
# 选择父元素下的子元素:soup.select('div > p')  # 返回所有 <div> 下的直接子元素 <p>
# 选择具有特定属性的元素:soup.select('[attr-name="attr-value"]')  # 返回具有指定属性名和属性值的元素对象
soup = BeautifulSoup(html_doc, 'html.parser')
links = soup.select('a')
# 使用 CSS 选择器 a 选取了所有 <a> 标签。接着,我们使用循环遍历选取到的元素,并打印出它们的 href 属性值。
for link in links:
    print(link['href'])

 使用lxml库解析HTML内容

from lxml import etree
# 从文件中加载HTML内容
with open('formatted_html.html', 'r', encoding='utf-8') as file:
    html_content = file.read()
# 使用lxml库解析HTML内容
tree = etree.HTML(html_content)
# 使用XPath表达式选择所有链接元素
links = tree.xpath('//a')
# 遍历并打印所有链接的文本和URL
for link in links:
    link_text = link.text
    link_url = link.get('href')
    print(f"Text: {link_text} \t URL: {link_url}")

 使用 prettify() 方法将文档格式化输出

import requests
from bs4 import BeautifulSoup

# 发送 GET 请求获取网页内容
url = 'https://www.cnbc.com/world/'
response = requests.get(url)
html_content = response.text

# 使用 Beautiful Soup 解析 HTML 内容
soup = BeautifulSoup(html_content, 'html.parser')

# 使用 prettify() 方法将文档格式化输出
formatted_html = soup.prettify()

# 将格式化后的文档输出到文件
with open('formatted_html.html', 'w', encoding='utf-8') as file:
    file.write(formatted_html)


# 选择所有段落元素并打印它们的文本内容
paragraphs = soup.find_all('p')
for p in paragraphs:
    print(p.get_text())


# 选择表格元素并提取表格数据
table = soup.find('table')
rows = table.find_all('tr')
for row in rows:
    cells = row.find_all('td')
    for cell in cells:
        print(cell.get_text())



# 使用 CSS 选择器选择所有链接元素
links = soup.select('a')

# 遍历并打印所有链接的文本和URL
for link in links:
    link_text = link.get_text()
    link_url = link.get('href')
    print(f"Text: {link_text} \t URL: {link_url}")

# find() 方法用于查找符合条件的第一个标签或属性,并返回该对象;
# find_all() 方法用于查找符合条件的所有标签或属性,并返回一个列表。

from bs4 import BeautifulSoup

html_doc = """
<html>
<head>
<title>Example Page</title>
</head>
<body>
<p>This is the first paragraph.</p>
<p class="important">This is the second paragraph.</p>
<p id="third">This is the third paragraph.</p>
</body>
</html>
"""
# find() 方法用于查找符合条件的第一个标签或属性,并返回该对象;
# find_all() 方法用于查找符合条件的所有标签或属性,并返回一个列表。
# 这两个方法的参数可以是标签名、属性名、属性值、正则表达式等。
soup = BeautifulSoup(html_doc, 'html.parser')
second_paragraph = soup.find('p', class_='important')
print(second_paragraph)

  • 7
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
使用BeautifulSoup解析HTML可以按照以下步骤进行: 1. 安装BeautifulSoup库:首先,你需要安装BeautifulSoup库。可以使用pip命令在命令行中执行以下命令进行安装: ``` pip install beautifulsoup4 ``` 2. 导入BeautifulSoup库:在Python脚本中,导入BeautifulSoup库以便使用它的功能: ```python from bs4 import BeautifulSoup ``` 3. 读取HTML文件或HTML字符串:使用open函数读取HTML文件,或者直接将HTML字符串传递给BeautifulSoup对象: ```python # 读取HTML文件 with open('example.html', 'r') as file: html = file.read() # 或者直接传递HTML字符串 html = '<html><body><h1>Hello, World!</h1></body></html>' # 创建BeautifulSoup对象 soup = BeautifulSoup(html, 'html.parser') ``` 4. 解析HTML内容使用BeautifulSoup对象的方法和属性来解析HTML内容。以下是一些常用的方法和属性: - find():查找第一个匹配的元素。 - find_all():查找所有匹配的元素。 - select():使用CSS选择器查找元素。 - get_text():获取元素的文本内容。 - attrs:获取元素的属性。 例如,要查找所有的`<a>`标签并获取它们的链接和文本内容,可以使用以下代码: ```python # 查找所有的<a>标签 links = soup.find_all('a') # 遍所有的<a>标签 for link in links: # 获取链接和文本内容 href = link['href'] text = link.get_text() print(href, text) ``` 这是使用BeautifulSoup解析HTML的基本步骤。你可以根据具体的需求使用BeautifulSoup提供的功能来处理HTML文档。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值