当前位置:网站首页>【爬虫】数据提取之xpath
【爬虫】数据提取之xpath
2022-07-04 22:46:00 【语音不识别】
安装
pip install lxml
导包
from lxml import etree
使用
将html字符串 转换为element对象
# 将html字符串 转换为element对象
from lxml import etree
element = etree.HTML(html_str)
以下是通过element对象.xpath('匹配规则')来提取内容
获取标签
使用 / 表示根节点,路径和路径之间的过渡
/html/xx/xx/xxx
使用 // 跨节点选取,直接到想要的标签或者文本
//xxx # 获取所有xxx标签
使用.
./ 当前节点
使用 ..
../ # 当前节点的上一级节点
.// 当不是完整的html时,使用 ,获取相对路径
获取属性
@属性名 获取当前标签 这个属性对应的属性值
//img/@src # 所有img 的scr属性
获取文本
/text() 获取标签里面的文本内容//标签名[contains( text() , ' 文字 ' ) ] 获取包含 文字的 标签
//ol/li//span[contains(text(),'可播放')]
获取特定条件标签
//标签名[@属性名=值] 根据标签的属性值去定位具体的标签
//span[@class='title'] # 可以通过类名进行获取了
//标签名[索引] 索引从1开始
从前边获取//上一级标签/标签名[position()>3] 从第4个开始
从后边获取//上一级标签/标签名[last()] 获取最后一个//上一级标签/标签名[last() - 2] 倒数第3个
结合//ol/li[position()>1][position()<last()-2]
//标签名[text()='值'] 根据标签中具体的文本内容定位具体的标签,需要一字不差进行匹配
//ol/li//span[text()='[可播放]'] # 匹配标签内容是[可播放]的标签
边栏推荐
- Redis入门完整教程:集合详解
- Excel 快捷键-随时补充
- P2181 diagonal and p1030 [noip2001 popularization group] arrange in order
- 【剑指offer】1-5题
- Redis introduction complete tutorial: List explanation
- Attack and defense world misc advanced zone 2017_ Dating_ in_ Singapore
- Redis入门完整教程:发布订阅
- Duplicate ADMAS part name
- Record: how to scroll screenshots of web pages on Microsoft edge in win10 system?
- C语言快速解决反转链表
猜你喜欢

实战模拟│JWT 登录认证

On-off and on-off of quality system construction

【剑指offer】1-5题

Unity Xiuxian mobile game | Lua dynamic sliding function (specific implementation of three source codes)

cout/cerr/clog的区别

Excel 快捷键-随时补充

Qt个人学习总结
![P2181 对角线和P1030 [NOIP2001 普及组] 求先序排列](/img/79/36c46421bce08284838f68f11cda29.png)
P2181 对角线和P1030 [NOIP2001 普及组] 求先序排列
![[Jianzhi offer] 6-10 questions](/img/73/5974068008bcdc9a70b3f5f57f1eb0.png)
[Jianzhi offer] 6-10 questions

ETCD数据库源码分析——处理Entry记录简要流程
随机推荐
[Lua] Int64 support
ECS settings SSH key login
企业如何跨越数字化鸿沟?尽在云原生2.0
A complete tutorial for getting started with redis: redis shell
Erik baleog and Olaf, advanced area of misc in the attack and defense world
A complete tutorial for getting started with redis: understanding and using APIs
Redis入门完整教程:集合详解
[OpenGL] note 29 anti aliasing (MSAA)
Redis introduction complete tutorial: slow query analysis
Redis入门完整教程:API的理解和使用
数据库基础知识
【图论】拓扑排序
Redis démarrer le tutoriel complet: Pipeline
qt绘制网络拓补图(连接数据库,递归函数,无限绘制,可拖动节点)
Google Earth engine (GEE) - tasks upgrade enables run all to download all images in task types with one click
Explanation of bitwise operators
Redis: redis configuration file related configuration and redis persistence
Tweenmax emoticon button JS special effect
Attack and defense world misc advanced area can_ has_ stdio?
Common methods in string class