博客
关于我
【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/

你可能感兴趣的文章
MySql创建数据表
查看>>
MySQL创建新用户以及ERROR 1396 (HY000)问题解决
查看>>
MySQL创建用户与授权
查看>>
MySQL创建用户报错:ERROR 1396 (HY000): Operation CREATE USER failed for 'slave'@'%'
查看>>
MySQL创建索引时提示“Specified key was too long; max key length is 767 bytes”
查看>>
mysql初始密码错误问题
查看>>
MySQL删除数据几种情况以及是否释放磁盘空间【转】
查看>>
Mysql删除重复数据通用SQL
查看>>
mysql判断某一张表是否存在的sql语句以及方法
查看>>
mysql加入安装策略_一键安装mysql5.7及密码策略修改方法
查看>>
mysql加强(1)~用户权限介绍、分别使用客户端工具和命令来创建用户和分配权限
查看>>
mysql加强(2)~单表查询、mysql查询常用的函数
查看>>
mysql加强(3)~分组(统计)查询
查看>>
mysql加强(4)~多表查询:笛卡尔积、消除笛卡尔积操作(等值、非等值连接),内连接(隐式连接、显示连接)、外连接、自连接
查看>>
mysql加强(5)~DML 增删改操作和 DQL 查询操作
查看>>
mysql加强(6)~子查询简单介绍、子查询分类
查看>>
mysql加强(7)~事务、事务并发、解决事务并发的方法
查看>>
MySQL千万级多表关联SQL语句调优
查看>>
mysql千万级大数据SQL查询优化
查看>>
MySQL千万级大表优化策略
查看>>