基于bs4库的HTML内容遍历

一、HTML基本格式

本文关于HTML文档树(或者标签树)的遍历,那么HTML的基本格式是什么呢?(从别处找的两张图)

                                      

按照遍历的方向来可划分为:上行遍历、下行遍历和平行遍历,html内容中的标签都是有所属关系的(该标签包含那些标签,该标签属于哪个标签)。图中红色箭头表示下行遍历,蓝色箭头表示上行遍历,黄色箭头表示平行遍历。

二、下行遍历

属性 说明
.contents 子节点的列表,将<tag>所有儿子节点存入列表
.children 子节点的迭代类型,与.contents类似,用于循环遍历儿子节点
.descendants 子孙节点的迭代类型,包含所有子孙节点,用于循环遍历

代码演示

from bs4 import BeautifulSoup

html = '<html><head><title>这是标题</title></head>\
       <body><p><b>这是第一段</b></p>\
       <p><b>这是第二段</b></p>\
       </body></html>'

soup = BeautifulSoup(html,'html.parser')#使用html.parser解析器

print(soup.body.contents)
print('*'*30)

for child in soup.body.children:#遍历儿子节点
	print(child)
print('*'*30)

for child in soup.body.descendants:#遍历子孙节点
	print(child)

运行结果

三、上行遍历

属性 说明
.parent 节点的父亲标签
.parents 节点先辈标签的迭代类型,用于循环遍历先辈节点

代码演示

from bs4 import BeautifulSoup

html = '<html><head><title>这是标题</title></head>\
       <body><p><b>这是第一段</b></p>\
       <p><b>这是第二段</b></p>\
       </body></html>'

soup = BeautifulSoup(html,'html.parser')#使用html.parser解析器

print(soup.title.parent)#查看title标签的父亲节点标签
print(soup.html.parent)#查看html标签的父亲节点标签,无父亲节点时显示当前标签
print('*'*30)

for parent in soup.p.parents:#上行遍历
    if parent is None :
        print(parent)
    else:
        print(parent.name)

运行结果

四、平行遍历

属性 说明
.next_sibling 返回按照HTML文本顺序的下一个平行节点标签
.previous_sibling 返回按照HTML文本顺序的上一个平行节点标签
.next_siblings 迭代类型,返回按照HTML文本顺序的后续所有平行节点标签
.previous_siblings 迭代类型,返回按照HTML文本顺序的前续所有平行节点标签

代码演示

from bs4 import BeautifulSoup

html = '<html><head><title>这是标题</title></head>\
       <body><p><b>这是第一段</b></p>\
       <p><b>这是第二段</b></p>\
       </body></html>'

soup = BeautifulSoup(html,'html.parser')#使用html.parser解析器

for sibling in soup.body.previous_siblings:#遍历前续节点,后续节点next_siblings同理
	print(sibling)

运行结果

发布了19 篇原创文章 · 获赞 2 · 访问量 2195

猜你喜欢

转载自blog.csdn.net/xiaoyeren_ITRoad/article/details/104704133