博客
关于我
【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进阶 with-as 性能调优
查看>>
mysql进阶-查询优化-慢查询日志
查看>>
wargame narnia writeup
查看>>
MySQL进阶篇SQL优化(InnoDB锁问题排查与解决)
查看>>
Mysql进阶索引篇03——2个新特性,11+7条设计原则教你创建索引
查看>>
mysql远程连接设置
查看>>
MySql连接出现1251Client does not support authentication protocol requested by server解决方法
查看>>
Mysql连接时报时区错误
查看>>
MySql连接时提示:unknown Mysql server host
查看>>
MySQL连环炮,你扛得住嘛?
查看>>
mysql逗号分隔的字符串如何搜索
查看>>
MySQL通用优化手册
查看>>
Mysql通过data文件恢复
查看>>
MYSQL遇到Deadlock found when trying to get lock,解决方案
查看>>
MYSQL遇到Deadlock found when trying to get lock,解决方案
查看>>
mysql部署错误
查看>>
MySQL配置信息解读(my.cnf)
查看>>
Mysql配置文件my.ini详解
查看>>
MySQL配置文件深度解析:10个关键参数及优化技巧---强烈要求的福利来咯。
查看>>
Mysql配置表名忽略大小写(SpringBoot连接表时提示不存在,实际是存在的)
查看>>