1. 模块简介
Beautiful Soup是一个Python库,用于从HTML和XML文件中提取数据。它可以帮助开发者通过简单的Python代码解析复杂的HTML和XML文档,提取出特定的数据和标签。Beautiful Soup提供了一些强大的解析器,包括Python标准库中的解析器以及第三方库lxml和html5lib。它也可以处理不完整或损坏的文档,并尽可能地还原它们的结构。Beautiful Soup还具有强大的搜索功能,可以根据标签、属性、文本内容等条件查找特定的元素。由于其易用性和灵活性,Beautiful Soup被广泛用于Web爬虫和数据分析等领域。为了方便描述,本文接下来将Beautiful Soup模块简写为BS模块。
2. Tag操作
'''
BS4模块-Tag
'''
from bs4 import BeautifulSoup
# 1.设置HTML字符串
html = """
<html lang="en">
<head>
<meta charset="UTF-8">
<title>美丽肥皂大学习</title>
</head>
<body>
<p class="title" name="jack">
<b>The Dormouse's story</b>
</p>
<p class="story">
The Story of Sun Wukong and Bai Gu Jing
<a href="http://www.jsnu.edu.cn/djs"
class="sister"
id="link1">
<!--花瓣网-->
</a>
<a href="http://www.jsnu.edu.cn/pyq"
class="sister"
id="link2">
悟空租车
</a>
<a href="http://www.jsnu.edu.cn/zih"
class="sister"
id="link3">
天成花园
</a>
The Story of Monks, Taoists, and Nuns
</p>
<p class="story">
.........
</p>
</body>
</html>
"""
# 2.转换bs4对象
soup = BeautifulSoup(html,'lxml')
# 3.获取title标签
print("3.获取title标签:",soup.title)
# 4.获取所有的a标签(默认只匹配第一个)
print("4.获取所有的a标签:",soup.a)
# <class 'bs4.element.Tag'>
print("4.获取所有的a标签类型:",type(soup.a))
# 5.获取p标签
print("5.获取p标签:",soup.p)
# 6.获取head标签
# head
print("6.获取head标签的名称:",soup.head.name)
# 7.获取p标签的attrs属性以及值
# {'class': ['title'], 'name': 'jack'}
print("7.获取p标签的attrs属性以及值:",soup.p.attrs)
# 8.获取p标签的属性以及值
print("8.获取p标签中的某属性值:",soup.p['class'])
print("8.获取p标签中的某属性值:",soup.p['name'])
# 9.删除p标签的属性的值
del soup.p['class']
print("9.删除p标签的属性值:",soup.p)
# 10.修改p标签的属性值
soup.p['name'] = 'wjj'
print("10.修改p标签的属性值:",soup.p)
# 11.增加p标签的menu属性
soup.p['menu'] = 'zpx'
print("11.增加p标签的属性值:",soup.p)
3. 遍历文档树
'''
BS4模块-遍历文档树
'''
from bs4 import BeautifulSoup
# 解析hello2.html为bs4对象
soup = BeautifulSoup(open("hello2.html",encoding='utf-8'),'lxml')
# 1.直接子节点
# 1.1 .content
# ['\n', <meta charset="utf-8"/>, '\n', <title>IloveBeau</title>, '\n']
print("1.1 .content:",soup.head.contents)
# 1.2 .children
# <list_iterator object at 0x0000016161F16FD0>
print("1.2 .children:",soup.head.children)
for child in soup.head.children:
print(child)
# 2.所有的子孙节点 .descendants属性
# 这里是从document开始的遍历与递归
for child in soup.descendants:
print(child)
# 3.节点内容.string属性
for child in soup.p.children:
print('child遍历:',child.string)
for desc in soup.descendants:
print("遍历文档树:",desc.string)
4.搜索文档树
'''
BS4模块-搜索文档树
'''
from bs4 import BeautifulSoup
import re
# 解析bs4对象
soup = BeautifulSoup(open("hello2.html",encoding='utf-8'),'lxml')
# 1.find_all方法
# 1.1 name参数
# 1.1.1 传入字符串
print("1.find_all-name参数-传入字符串:",soup.find_all("b"))
# 1.1.2 传入正则表达式
# 匹配以b开头的标签
pattern = re.compile("^b")
for tag in soup.find_all(pattern):
print("1.find_all-name参数-传入正则表达式:",tag.name)
# 1.1.3 传入列表
print("1.find_all-name参数-传入列表:",soup.find_all(['a','b']))
# 1.2 keyword参数
print("1.find_all-keyword参数:",soup.find_all(id='link2'))
# 1.3 text参数
# 1.3.1 传入字符串
print("1.find_all-text参数-传入字符串:",soup.find_all(text="黄明昊"))
# 1.3.2 传入正则表达式
pattern = re.compile("Story")
print("1.find_all-text参数-传入正则表达式:",soup.find_all(text=pattern))
# 1.3.3 传入列表
print("1.find_all-text参数-传入列表:",
soup.find_all(text=['蔡徐坤','陈立农','范丞丞']))
5. CSS选择器
'''
BS4模块-CSS选择器
'''
from bs4 import BeautifulSoup
# 解析
soup = BeautifulSoup(open("hello2.html",encoding='utf-8'),'lxml')
# 1.通过标签名查找
print("1.通过标签名查找:",soup.select("title"))
print("1.通过标签名查找2:",soup.select("a"))
# 2.通过类名查找
print("2.通过类名查找:",soup.select(".sister"))
# 3.通过id名查找
print("3.通过id名查找:",soup.select("#link1"))
# 4.组合查找
# 空格 p标签下面所有的子标签
# > 指的是head标签指定的标签名
print("4.通过组合查找:",soup.select("p #link1"))
print("4.通过组合查找:",soup.select("head > title"))
# 5.属性查找
print("5.属性查找:",soup.select("a[class='sister']"))
print("5.属性查找+组合查找:",soup.select("p a[class='sister']"))
# 6.获取内容
print("6.获取标签内容:",soup.select("title"))
print("6.获取标签内容:",soup.select("title")[0].get_text())