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

你可能感兴趣的文章
Python+pytest接口自动化之cookie绕过登录(保持登录状态)
查看>>
python+pytest接口自动化:接口测试
查看>>
Python+requests+unittest执行接口自动化测试详情
查看>>
Python+requests+unittest执行接口自动化测试详情
查看>>
python+requests+unittest执行自动化接口测试!
查看>>
Python+Requests编码识别Bug
查看>>
python函数编写_[零基础学python]传说中的函数编写条规
查看>>
Python+selenium —— UI自动化之鼠标操作
查看>>
python函数注释,参数后面加冒号:,函数后面的箭头→是什么?
查看>>
Python+Selenium+Threading进行兼容性测试
查看>>
Python+selenium+unittest的GUI自动化框架实现
查看>>
python函数拟合不规则曲线_Python计算&绘图——曲线拟合问题(转)
查看>>
python函数定义的基本格式_零基础学python-2.19 定义函数、调用函数与默认参数
查看>>
Python+Selenium之数据驱动测试的实现
查看>>
python函数定义与使用+返回值简解
查看>>
Python+Selenium登录
查看>>
Python日期时间模块
查看>>
Python函数合集:足足68个内置函数请收好!
查看>>
Python+Selenium自动化测试项目实战
查看>>
Python+Selenium自动化测试项目实战【建议收藏】
查看>>