bs4简介
基本概念
Beautiful Soup 是⼀个可以从HTML或XML⽂件中提取数据的⽹⻚信息提取库
安装
- pip install lxml
- pip install bs4
bs4的使用
快速使用
html_doc = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title"><b>The Dormouse's story</b></p>
<p class="story">Once upon a time there were three little sisters; and their names were
<a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>,
<a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
<a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;
and they lived at the bottom of a well.</p>
<p class="story">...</p>
#获取bs对象
bs=Beautifulsoup(html_doc,'lxml)
#打印文档内容(把我们的标签更加规范的打印)
print(bs.prettify())
print(bs.title) #获取title标签内容 <title>The Dormouse's story</title>
print(bs.title.name) #获取title标签名称 title
print(bs.title.string) #title标签里面的文本内容 The Dormouse's story
print(bs.p) #获取p段落
bs的对象种类
- tag:标签
- NavigableString:可导航的字符串
- BeautifulSoup:bs对象
- Comment:注释
遍历文档树 遍历子节点
bs里面有三种情况,第一个是遍历,第二个是查找,第三个是修改
** Contents children descendants **
- Contents 返回的是一个所有子节点的列表
- children 返回的是一个子节点的迭代器
- descendants 返回的是一个生成器遍历子子孙孙
** string strings stripped string** - string 获取标签里面的内容
- strings 返回一个生成器对象,用来获得多个标签内容
- stripped strings 和strings基本一致,但是他可以把多余的空格去掉
遍历文档树 遍历父节点
parent parents
- parent 直接父节点
- parents 获取所有的父节点
遍历文档树 遍历兄弟节点 - next_sibling 下一个兄弟节点
- previous_sibling 上一个兄弟节点
- next_siblings 下一个所有兄弟节点
- previous_siblings 上一个所有兄弟节点
搜索树 - 字符串过滤器
- 正则表达式过滤器
我们用正则表达式里面compile方法编译一个正则表达式传给find或者findall,这个方法可以实现一个正则表达式的一个过滤器的搜索 - 列表过滤器
- True过滤器
- 方法过滤器
find_all()和find()
find_all()
- find_all()方法已列表形式返回所有的搜索到的标签数据
- find()方法返回搜索到的第一个数据
- find_all()方法参数
def find_all(self, name=None, attrs={}, recursive=True, text=None, limit=None, **kwargs):
- name:tag名称
- attr:标签的属性
- recursive:是否递归搜索
- text:文本内容
- limit:限制返回条数
- kwargs:关键字参数
select()方法
我们也可以通过css选择器的方式来提取数据。但是需要注意的是需要我们掌握css语法
https://www.w3school.com.cn/cssref/css_selectors.asp
修改文档树
- 修改tag的名称和属性
- 修改string属性赋值,就相当于用当前的内容替代原来的内容
- append() 向tag中添加内容,就好像python的列表append()方法
- decompose() 修改删除段落,对于一些没有必要的文章段落我们可以将他删除