Beautiful Soup

本文介绍了如何使用Python库BeautifulSoup从网页中提取信息,涵盖了安装、常用对象如BeautifulSoup、Tag、NavigableString和Comment的使用,以及find_all和find函数的示例。同时,详细解释了子节点、父节点和兄弟节点的概念。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、介绍及安装

Beautiful Soupn是一个可以从网页中提取信息的Python库

官方文档:https://www.crummy.com/software/BeautifulSoup/bs4/doc.zh/

安装

pip install beautifulsoup4

导入 

from bs4 import BeautifulSoup

二、四大常用对象

1-BeautifulSoup对象

BeautifulSoup(text)----表示的是一个文档的全部内容

prettify()---按照标准的缩进格式的结构输出

get_text()---会将HTML文档中的所有标签清除,返回一个只包含文字的字符串

from bs4 import BeautifulSoup

text = '''
<?xml version="1.0" encoding="ISO-8859-1"?>

<bookstore>

<book>
  <title lang="eng">Harry Potter</title>
  <price>29.99</price>
</book>

<book>
  <title lang="eng">Learning XML</title>
  <price>39.95</price>
</book>

</bookstore>
'''

# # 创建一个Beautiful Soup对象
soup = BeautifulSoup(text, 'lxml')
print(soup)

# 按照标准的缩进格式输出
r = soup.prettify()
print(r)

# 获取所有文字内容
r = soup.get_text()
print(r)
输出结果:
Harry Potter
29.99


Learning XML
39.95

2-Tag

Tag是HTML中的一个标签,有name和attrs两个属性

from bs4 import BeautifulSoup

text = '''
<?xml version="1.0" encoding="ISO-8859-1"?>

<bookstore>

<book>
  <title lang="eng">Harry Potter</title>
  <price>29.99</price>
</book>

<book>
  <title lang="eng">Learning XML</title>
  <price>39.95</price>
</book>

</bookstore>
'''

# Tag
tag = soup.title
print(tag)
输出结果:
<title lang="eng">Harry Potter</title>

# name属性
print(tag.name)
输出结果:
title

# 获取标签的属性
print(tag.attrs)
输出结果:
{'lang': 'eng'}

# 单独获取某个属性
r = soup.title['lang']
print(r)
输出结果:
eng

3-NavigableString

获取标签中的文字

# NavigableString
print(tag.string)  # 获取标签中的文字
输出结果:
Harry Potter

4-Comment

Comment 对象是一个特殊类型的 NavigableString 对象

输出的内容中不包括注释符号

# Comment对象
string = '<p><!--这是注释!--></p>'
sp = BeautifulSoup(string, 'lxml')
print(sp.p)  # 获取p标签
输出结果:
<p><!--这是注释!--></p>

# 获取标签中的文字
print(sp.p.string)
输出结果:
这是注释!


print(type(sp))-------<class 'bs4.BeautifulSoup'>

print(type(sp.p))------<class 'bs4.element.Tag'>

print(type(sp.p.string))------<class 'bs4.element.Comment'>

三、两个常用函数

1-find_all()--返回结果是值包含一个元素的列表

2-find()--直接返回第一个结果

from bs4 import BeautifulSoup

text = '''
<?xml version="1.0" encoding="ISO-8859-1"?>

<bookstore>

<book>
  <title lang="eng">Harry Potter</title>
  <price>29.99</price>
</book>

<book>
  <title lang="eng">Learning XML</title>
  <price>39.95</price>
</book>

</bookstore>
'''

# 创建一个Beautiful Soup对象
soup = BeautifulSoup(text, 'lxml')

# 两个常用函数
r1 = soup.find_all('title')
print(r1)
输出结果:
[<title lang="eng">Harry Potter</title>, <title lang="eng">Learning XML</title>]

r2 = soup.find('title')
print(r2)
输出结果:
<title lang="eng">Harry Potter</title>

find_all()

r3 = soup.find_all('title', lang='eng')   # 查找指定的标签
print(r3)
输出结果:
[<title lang="eng">Harry Potter</title>, <title lang="eng">Learning XML</title>]


# 获取符合条件的结果中的第1条
r4 = soup.find_all('title', lang='eng')[0]
print(r4)
输出结果:
<title lang="eng">Harry Potter</title>

# 获取符合条件的结果中的第1条中的文本
r5 = soup.find_all('title', lang='eng')[0].get_text()
print(r5)
输出结果:
Harry Potter

r6 = soup.find_all(['title', 'price'])
print(r6)
输出结果:
[<title lang="eng">Harry Potter</title>, <price>29.99</price>, 
 <title lang="eng">Learning XML</title>, <price>39.95</price>]

四、三大常见节点

1-子节点:一个Tag可能包含多个字符串或其它的Tag,这些都是这个Tag的子节点

2-父节点:每个tag或字符串都有父节点:被包含在某个tag中

3-兄弟节点:平级的节点

from bs4 import BeautifulSoup

text = '''
<?xml version="1.0" encoding="ISO-8859-1"?>

<bookstore>

<book>
  <title lang="eng">Harry Potter</title>
  <price>29.99</price>
</book>

<book>
  <title lang="eng">Learning XML</title>
  <price>39.95</price>
</book>

</bookstore>
'''

# 创建一个Beautiful Soup对象
soup = BeautifulSoup(text, 'lxml')

# ***********子节点***********

# 获取book标签的信息
r6 = soup.book
print(r6)
输出结果:
<book>
<title lang="eng">Harry Potter</title>
<price>29.99</price>
</book>

# 获取book标签下的所有子节点
r7 = soup.book.contents
print(r7)
输出结果:
['\n', <title lang="eng">Harry Potter</title>, '\n', <price>29.99</price>, '\n']

# 获取book标签下子节点的第4个元素
r8 = soup.book.contents[3]
print(r8)
输出结果:
<price>29.99</price>

# ***********父节点**************
# 父节点
r = soup.title.parent
print(r)
输出结果:
<book>
<title lang="eng">Harry Potter</title>
<price>29.99</price>
</book>

r = soup.book.parent
print(r)
输出结果:
<bookstore>
<book>
<title lang="eng">Harry Potter</title>
<price>29.99</price>
</book>
<book>
<title lang="eng">Learning XML</title>
<price>39.95</price>
</book>
</bookstore>

# .parents,获取全部父节点
for parent in soup.title.parents:
    print(parent.name)
输出结果:
book
bookstore
body
html
[document]

# 兄弟节点
# .next_sibling,获取该节点的下一个兄弟节点
r = soup.book.next_sibling
print(r)
输出结果:
'\n'

# .next_sibling,获取该节点的上一个兄弟节点
r = soup.book.previous_sibling
print(r)
输出节点:
'\n'

# .next_siblings:获取全部兄弟节点
for sibling in soup.title.next_siblings:
    print(sibling)

输出结果:
'\n','\n','<price>29.99</price>'

 

### Beautiful Soup Python 库的使用方法和示例 #### 安装 Beautiful Soup 要使用 Beautiful Soup,首先需要安装该库。可以通过 `pip` 工具来完成安装过程。以下是安装命令: ```bash pip install beautifulsoup4 ``` 此外,由于 Beautiful Soup 常常依赖于解析器(如 lxml 或 html5lib),建议一并安装这些工具以获得更好的性能和支持。 ```bash pip install lxml pip install html5lib ``` #### 导入 Beautiful Soup 并初始化对象 在导入 Beautiful Soup 后,可以将其应用于 HTML 或 XML 数据的解析。通常会通过字符串形式加载数据或将 URL 请求返回的内容传递给它。以下是一个简单的例子展示如何创建一个 BeautifulSoup 对象[^1]: ```python from bs4 import BeautifulSoup html_doc = """ <html><head><title>Test Page</title></head> <body> <p class="description">This is a test paragraph.</p> <a href="https://example.com">Example Link</a> </body></html> """ # 初始化 BeautifulSoup 对象 soup = BeautifulSoup(html_doc, 'lxml') print(soup.prettify()) ``` 上述代码展示了如何定义一段 HTML 字符串并通过指定解析器 `'lxml'` 创建了一个 BeautifulSoup 实例。最后调用了 `.prettify()` 方法使输出更美观[^3]。 #### 查找单个元素 Beautiful Soup 支持多种方式查找特定节点或属性值。例如,如果想找到第一个 `<p>` 标签,则可如下实现: ```python paragraph = soup.find('p') # 找到第一个 p 标签 print(paragraph.text.strip()) # 输出:This is a test paragraph. ``` 这里我们使用了 `.find()` 函数定位到了首个匹配项,并访问它的文本内容[^2]。 #### 查询多个相同类型的标签 当页面中有许多同类别的标签时,可以用 `.find_all()` 来获取它们列表形式的结果集: ```python all_links = soup.find_all('a') for link in all_links: print(link.get('href')) # 获取超链接地址 ``` 这段脚本遍历所有的锚点 (`<a>`) 元素并将各自的 HREF 属性打印出来。 #### 修改现有 DOM 结构 除了读取外,还可以借助 Beautiful Soup 动态调整文档结构。比如向某个段落追加额外文字或者替换掉原有链接目标等操作均被允许: ```python new_text = " Additional information." original_paragraph = soup.find('p', {'class': 'description'}) if original_paragraph: original_paragraph.string += new_text updated_link = soup.find('a') if updated_link and updated_link.has_attr('href'): updated_link['href'] = "http://modified.example.org" print(soup.body) ``` 此片段演示了怎样更新既有段落以及改变外部连接指向的行为模式。 --- ### 注意事项 尽管 Beautiful Soup 非常强大且易于上手,但在实际项目应用过程中仍需注意一些细节问题: - **选择合适的解析引擎**:虽然默认情况下会选择最兼容的方式工作,但如果遇到特殊编码或者其他复杂情况可能需要手动切换至其他选项。 - **效率考量**:对于大规模的数据采集任务而言,单纯依靠 Beautiful Soup 可能不是最佳方案;此时应该考虑结合其它高效框架一起协作完成作业。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值