Beautiful Soup库详解

Beautiful Soup库

Beautiful Soup库是解析、遍历、维护html“标签树”的功能库

from bs4 import BeautifulSoup
soup = BeautifulSoup('<p>data</p>','html.parser')
soup2 = BeautifulSoup(open("D://demo.html"),'html.parser')

BeautifulSoup库的解析器

解析器 使用方法 条件
bs4的HTML解析器 BeautifulSoup(mk,‘html.parser’) 安装bs4库
lxml的HTML解析器 BeautifulSoup(mk,‘lxml’) pip install lxml
lxml的XML解析器 BeautifulSoup(mk,‘xml’) pip install lxml
html5lib的解析器 BeautifulSoup(mk,‘html5lib’) pip install html5lib

Beautiful Soup类的基本元素

基本元素 说明
Tag 标签,最基本的信息组织单元,分别用<>和</>标明开头和结尾
Name 标签的名字,<’ p’>…</‘p’>的名字是’p’,格式:<‘tag’>.name
Attributes 标签的属性,字典形式组织,格式:<‘tag’>.attrs
NavigableString 标签内非属性字符串,<>…</>中字符串,格式:<‘tag’>.string
Comment 标签内字符串的注释部分,一种特殊的Comment类型

[外链图片转存失败(img-pcAOK7iV-1565059186556)(C:\Users\Jarrod\AppData\Roaming\Typora\typora-user-images\1564801437167.png)]

基于bs4库的HTML内容的遍历方法

[外链图片转存失败(img-DBwRiZ8y-1565059186560)(C:\Users\Jarrod\AppData\Roaming\Typora\typora-user-images\1564801896391.png)]

标签树的下行遍历
属性 说明
.contents 子节点的列表,将所有儿子节点存入列表
.children 子节点的迭代类型,与.contents类似,用于循环遍历儿子节点
.descendants 子孙节点的迭代类型,包括所有子孙节点,用于循环遍历
标签树的上行遍历
属性 说明
.parent 节点是父亲标签
.parents 节点先辈标签的迭代类型,用于循环遍历先辈节点

标签父节点名字的打印

soup = BeautifulSoup(demo,"html.parser")
for parent in soup.a.parents:
    if parent is None:
        print(parent)
    else:
        print(parent.name)
标签树是平行遍历
属性 说明
.next_sibling 返回按照HTML文本顺序的下一个平行节点标签
.previous_sibling 返回按照HTML文本顺序的上一个平行节点标签
.next_siblings 迭代类型,返回按照HTML文本顺序的后续所有平行节点标签
.previous_siblings 迭代类型,返回按照HTML文本顺序的前续所有平行节点标签

基于bs4库的HTML内容查找

<>.find_all(name,attrs,recursive,string,**kwargs)
# 返回一个列表类型,存储查找的结果。
name:对标签名称的检索字符串
attrs:对标签属性值的检索字符串,可标注属性检索。
recursive:是否对子孙全部检索,默认True。
string:<>...</>中字符串区域的检索字符串。
<tag>(..) 等价于 <tag>.find_all(..)
soup(..) 等价于 soup.find_all(..)

扩展方法

方法 说明
<>.find() 搜索且只返回一个结果,字符串类型
<>.find_parents() 在先辈节点中搜索,返回列表类型
<>.find_parent() 在先辈节点中返回一个结果,字符串类型
<>.find_next_siblings() 在后续平行节点中搜索,返回列表类型
<>.find_next_sibling() 在后续平行节点中返回一个结果,字符串类型
<>.find_previous_siblings() 在前续平行节点中搜索,返回列表类型
<>.find_previous_sibling() 在前续平行节点中返回一个结果,字符串类型

发布了31 篇原创文章 · 获赞 90 · 访问量 9955

猜你喜欢

转载自blog.csdn.net/Jarrodche/article/details/98594840
今日推荐