python网络爬虫和信息提取笔记之BeautifulSoup类

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

获取demo
import requests #引用requests库
r = requests.get("http://python123.io/ws/demo.html ") #获取该网页的源代码
demo = r.text #把demo定义为该网页的代码内容
demo #在IDLE下打印

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

soup = BeautifulSoup(demo, "html.parser")
soup.head #head标签
soup.head.contents #head儿子节点
soup.body.contents #body儿子节点,包括标签节点和字符串节点
len(soup.body.contents)#body的儿子节点的数量
soup.body.contents[1] #第一个儿子节点

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

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

soup = BeautifulSoup(demo, "html.parser")
soup.title.parent #title标签的父亲节点
soup.title.parent #title标签的父亲节点
soup.parent#没有解释,soup的父亲是空的

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

for sibling in soup.a.next_siblings:
    print(sibling)#遍历后续节点
for sibling in soup.a.previous_siblings:
    print(sibling)#遍历前续节点

平行遍历必须要发生在同一个父亲节点下的个节点间

from bs4 import BeautifulSoup
soup = BeautifulSoup(demo,"html.parser")
soup.prettify()#发现所有语句后面都加了 \n 换行符,prettify()也可以对单独一个标签起到作用,标签可以清晰漂亮的打印出来
print(soup.prettify())#解析html代码

猜你喜欢

转载自blog.csdn.net/weixin_42388440/article/details/81268753
今日推荐