博客
关于我
【Python3 爬虫学习笔记】解析库的使用 4 —— Beautiful Soup 2
阅读量:761 次
发布时间:2019-03-21

本文共 1675 字,大约阅读时间需要 5 分钟。

父节点和祖先节点

如果要获取某个节点元素的父节点,可以调用parent属性:

html = """The Dormouse's story

Once upon a time there were three little sisters; and their names wereElsie

...

"""from bs4 import BeautifulSoupsoup = BeautifulSoup(html, 'lxml')print(soup.a.parent)

运行结果如下:

Once upon a time there were three little sisters; and their names wereElsie

这里我们选择的是第一个a节点的父节点元素。很明显,它的父节点是p节点,输出结果便是p节点及其内部的内容。

需要注意的是,这里输出的仅仅是a节点的直接父节点,而没有再向外寻找父节点的祖先节点。如果想获取所有的祖先节点,可以调用parents属性:

html = """

Elsie

"""from bs4 import BeautifulSoupsoup = BeautifulSoup(html, 'lxml')print(type(soup.a.parents))print(list(enumerate(soup.a.parents)))

运行结果如下:

[(0,

Elsie

), (1,

Elsie

), (2,

Elsie

), (3,

Elsie

)]

可以发现,返回结果是生成器类型。这里用列表输出了它的索引和内容,而列表中的元素就是a节点的祖先节点。

兄弟节点

兄弟节点的获取方式:

html = """

Once upon a time there were little sisters; and their names wereElsie HelloLacie andTillie and they lived at the bottom of a well.

"""from bs4 import BeautifulSoupsoup = BeautifulSoup(html, 'lxml')print('Next Sibling', soup.a.next_sibling)print('Prev Sibling', soup.a.previous_sibling)print('Next Siblings', list(enumerate(soup.a.next_siblings)))print('Prev Siblings', list(enumerate(soup.a.previous_siblings)))

运行结果如下:

Next Sibling        HelloPrev Sibling        Once upon a time there were little sisters; and their names wereNext Siblings [(0, '\n        Hello\n'), (1, Lacie), (2, '\n        and\n'), (3, Tillie), (4, '\n        and they lived at the bottom of a well.\n')]Prev Siblings [(0, '\n        Once upon a time there were little sisters; and their names were\n')]

可以看到,这里调用了4个属性,其中next_sibling和previous_sibling分别获取节点的下一个和上一个兄弟元素,next_siblings和previous_siblings则分别返回所有前面和后面的兄弟节点的生成器。

转载地址:http://csyrz.baihongyu.com/

你可能感兴趣的文章
NetApp凭借领先的混合云数据与服务把握数字化转型机遇
查看>>
NetAssist网络调试工具使用指南 (附NetAssist工具包)
查看>>
Netbeans 8.1启动参数配置
查看>>
NetBeans IDE8.0需要JDK1.7及以上版本
查看>>
NetBeans之JSP开发环境的搭建...
查看>>
NetBeans之改变难看的JSP脚本标签的背景色...
查看>>
netbeans生成的maven工程没有web.xml文件 如何新建
查看>>
netcat的端口转发功能的实现
查看>>
NetCore 上传,断点续传,可支持流上传
查看>>
Netcraft报告: let's encrypt和Comodo发布成千上万的网络钓鱼证书
查看>>
Netem功能
查看>>
netfilter应用场景
查看>>
Netflix:当你按下“播放”的时候发生了什么?
查看>>
Netflix推荐系统:从评分预测到消费者法则
查看>>
netframework 4.0内置处理JSON对象
查看>>
Netgear WN604 downloadFile.php 信息泄露漏洞复现(CVE-2024-6646)
查看>>
Netgear wndr3700v2 路由器刷OpenWrt打造全能服务器(十一)备份
查看>>
netlink2.6.32内核实现源码
查看>>
netmiko 自动判断设备类型python_Python netmiko模块的使用
查看>>
NetMizer 日志管理系统 多处前台RCE漏洞复现
查看>>