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

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

BeautifulSoup 中父节点、祖先节点和兄弟节点操作

父节点和祖先节点

在BeautifulSoup中获取节点的父节点非常简单,可以通过节点的parent属性实现。每个节点都有一个父节点, Parents属性则返回该节点的所有祖先节点。

示例代码:

html = """

Elsie

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

示例输出:

[(0,

Elsie

兄弟节点

获取兄弟节点可以使用next_sibling``及其它相关属性。**next_sibling**和previous_sibling``获取的是下一个和上一个直接的兄弟节点,而next_siblingsprevious_siblings则返回所有兄弟节点包括中间有其他元素的空节点。

示例代码:

html = """

Once upon a time there were little sisters; and their names were Elsie Hello Lacie and Tillie 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')]

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

你可能感兴趣的文章
Pytest自动化测试-简易入门教程(02)
查看>>
Pytest自动化测试-简易入门教程(03)
查看>>
Pytest自动化测试指定执行测试用例
查看>>
Pytest自动化测试框架 fixture 传参实战
查看>>
pytest自动化测试框架pytest.ini配置文件详细
查看>>
Pytest自动化测试框架介绍
查看>>
Pytest自动化测试框架,建议收藏。
查看>>
Pytest自动化测试框架:mark用法---测试用例分组执行
查看>>
PyTorch 1.0 中文官方教程:强化学习 (DQN) 教程
查看>>
pytest:4种方法实现 - 重复执行用例 - 展示迭代次数
查看>>
Pytest:一个卓有成效的测试工具
查看>>
python
查看>>
Python "HTTP Error 403: Forbidden"
查看>>
python %ns的作用
查看>>
Python + Appium 之 APP 自动化测试,坑点汇总!(建议收藏)
查看>>
Python + Appium 自动化操作微信入门(超详细)
查看>>
Python + Pytest 自动化框架的用例依赖实操
查看>>
python进阶(8):yield函数
查看>>
Python + requests实现接口自动化测试!
查看>>
python + requests实现的接口自动化测试(超详细~)
查看>>