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

你可能感兴趣的文章
Open vSwitch实验常用命令
查看>>
Open WebUI 忘了登入密码怎么办?
查看>>
open***负载均衡高可用多种方案实战讲解02(老男孩主讲)
查看>>
Open-E DSS V7 应用系列之五 构建软件NAS
查看>>
Open-Sora代码详细解读(1):解读DiT结构
查看>>
Open-Sora代码详细解读(2):时空3D VAE
查看>>
Open-Source Service Discovery
查看>>
open-vm-tools-dkms : 依赖: open-vm-tools (>= 2:9.4.0-1280544-5ubuntu3) 但是它将不会被安装
查看>>
open3d-Dll缺失,未找到指定模块解决
查看>>
openai Midjourney代理服务 gpt大模型第三方api平台汇总 支持国内外各种大模型 持续更新中...
查看>>
OpenAll:Android打开组件新姿势【仅供用于学习了解ButterKnife框架基本原理】
查看>>
OpenASR 项目使用教程
查看>>
Openbox-桌面图标设置
查看>>
opencart出现no such file or dictionary
查看>>
OpenCV 3.1 imwrite()函数写入异常问题解决方法
查看>>
OpenCV 4.1.0版drawContours
查看>>
Opencv cv2.putText 函数详解
查看>>
opencv glob 内存溢出异常
查看>>
opencv Hog Demo
查看>>
opencv Hog学习总结
查看>>