文章目录
一. python使用xpath
使用时先安装 lxml 包
pip install lxml
二. xpath简介
XPath,全称 XML Path Language,即 XML 路径语言,它是一门在 XML 文档中查找信息的语言。XPath 可用来在 XML 文档中对元素和属性进行遍历。
- XPath 使用路径表达式在 XML 文档中进行导航
- XPath 包含一个标准函数库
- XPath 是 XSLT 中的主要元素
- XPath 是一个 W3C 标准
三. xpath语法
在 XPath 中,有七种类型的节点:元素、属性、文本、命名空间、处理指令、注释以及文档(根)节点。XML 文档是被作为节点树来对待的。树的根被称为文档节点或者根节点。
下面列出了最常用的表达式
通配符:
四. 实例
xml文件:
<?xml version="1.0" encoding="ISO-8859-1"?>
<bookstore>
<book>
<title lang="eng">Harry Potter</title>
<price>29.99</price>
</book>
<book>
<title lang="eng">Learning XML</title>
<price>39.95</price>
</book>
</bookstore>
简单的查找
谓语 & 查找特定的节点
通配符举例
选取若干路径
五. 常用函数
5.1 starts-with() 获取以xxx开头的元素
xpath(‘//div[stars-with(@class,”test”)]’)
7.2 ends_with() 以xxx结尾
xpath("//input[ends-with(@id,'fuck')]")
7.3 contains() 获取包含xxx的元素
xpath(‘//div[contains(@id,”test”)]’)
7.4 and 并且 同时
xpath("//input[@type='submit' and @name='fuck']")
7.5 or 或者
xpath("//input[@type='submit' or @name='fuck']")
7.6 not 非
xpath("//input[@type='submit' and not(contains(@name,'fuck'))]")
7.7 text()
xpath(‘//div[contains(text(),”test”)]’)
xpath(‘//div[@id=”“test]/text()’)
参考:
- https://www.bilibili.com/video/BV1wa41197X9
- https://blog.csdn.net/xiaoweite1/article/details/104433926/
- https://blog.csdn.net/weixin_38819889/article/details/103233148
- https://www.cnblogs.com/mxjhaima/p/13775844.html