当前位置:网站首页>【爬虫】数据提取之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()='[可播放]'] # 匹配标签内容是[可播放]的标签
边栏推荐
猜你喜欢
Explanation of bitwise operators
Unity vscode emmylua configuration error resolution
Redis入门完整教程:HyperLogLog
Network namespace
The overview and definition of clusters can be seen at a glance
debug和release的区别
qt绘制网络拓补图(连接数据库,递归函数,无限绘制,可拖动节点)
Redis入门完整教程:事务与Lua
cout/cerr/clog的区别
Attack and Defense World MISC Advanced Area Erik baleog and Olaf
随机推荐
Redis入门完整教程:初识Redis
qt绘制网络拓补图(连接数据库,递归函数,无限绘制,可拖动节点)
【剑指offer】1-5题
Detailed explanation of heap sort code
String类中的常用方法
Sword finger offer 67 Convert a string to an integer
HMS core unified scanning service
Unity Xiuxian mobile game | Lua dynamic sliding function (specific implementation of three source codes)
Create Ca and issue certificate through go language
ScriptableObject
Analysis of environmental encryption technology
剑指Offer 68 - II. 二叉树的最近公共祖先
【ODX Studio編輯PDX】-0.2-如何對比Compare兩個PDX/ODX文件
Unity vscode emmylua configuration error resolution
vim编辑器知识总结
How to send a reliable request before closing the page
Redis入门完整教程:发布订阅
LIst 相关待整理的知识点
[Jianzhi offer] 6-10 questions
Redis入门完整教程:键管理