Beautiful Soup 是 Python 中一个非常流行的 HTML/XML 解析库,它提供了一些重要的概念和方法来帮助我们对 HTML/XML 进行解析和处理。下面是一些 Beautiful Soup 中的重要概念:
-
标签(Tag):在 HTML/XML 中,标签用于定义文档的结构和内容。Beautiful Soup 可以通过搜索和遍历文档中的标签来获取其内容和属性。
-
属性(Attribute):HTML/XML 标签可以包含一些属性,如
class
、id
、href
等。Beautiful Soup 可以通过搜索和遍历文档中的属性来获取其值。 -
NavigableString:表示 Beautiful Soup 所解析的 HTML/XML 文档中的字符串。NavigableString 对象通常是 HTML/XML 标签中的文本内容。
-
BeautifulSoup 对象:表示整个 HTML/XML 文档,在 Beautiful Soup 中创建该对象后,我们可以通过它来访问文档的各个部分,包括文档中的标签、字符串等。
-
遍历和搜索方法:Beautiful Soup 提供了多种方法来搜索和遍历 HTML/XML 文档中的标签和属性。比如
find()
和find_all()
方法可以用来搜索特定的标签或属性,children
和descendants
属性可以用来遍历文档中的标签等。 -
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)