当前位置:网站首页>XPath超详细总结
XPath超详细总结
2022-07-13 18:06:00 【偷完面具就瞎跑】
XPath
XPath,全称 XML Path Language,即 XML 路径语⾔,它是⼀⻔在 XML ⽂档中查找信息的语⾔。最初是⽤来搜寻 XML ⽂档的,但同样适⽤于 HTML ⽂档的搜索。所以在做爬⾍时完全可以使⽤ XPath做相应的信息抽取。
1、XPath概览
XPath 的选择功能⼗分强⼤,它提供了⾮常简洁明了的路径选择表达式。另外,它还提供了超过100 个内建函数,⽤于字符串、数值、时间的匹配以及节点、序列的处理等,⼏乎所有想要定位的节点都可以⽤ XPath 来选择。
官⽅⽂档: https://www.w3.org/TR/xpath/
2、XPath常用规则

这里列出了XPath的常用规则, 示例如下:
//title[@lang=‘eng’]
这是⼀个 XPath 规则,代表的是选择所有名称为 title,同时属性 lang 的值为 eng 的节点,后⾯会
通过 Python 的 lxml 库,利⽤ XPath 进⾏ HTML 的解析。
3、安装
windows—>pyton3环境下: pip install lxml
linux环境下: pip install lxml
4、实例引入
from lxml import etree
text = ''
<div>
<ul>
<li class="item-0"><a href="link1.html">first item</a></li>
<li class="item-1"><a href="link2.html">second item</a></li>
<li class="item-inactive"><a href="link3.html">third item</a></li>
<li class="item-1"><a href="link4.html">fourth item</a></li>
<li class="item-0"><a href="link5.html">fifth item</a>
</ul>
</div>
⾸先导⼊ lxml 库的 etree 模块,然后声明⼀段 HTML ⽂本,调⽤ HTML 类进⾏初始化,成功构造⼀个 XPath 解析对象。注意: HTML ⽂本中最后⼀个 li 节点没有闭合,但是 etree 模块可以⾃动修正HTML ⽂本。调⽤ tostring() ⽅法即可输出修正后的 HTML 代码,但结果是 bytes 类型,可以⽤decode() ⽅法将其转化为 str 类型,结果如下:
<html><body><div>
<ul>
<li class="item-0"><a href="link1.html">first item</a></li>
<li class="item-1"><a href="link2.html">second item</a></li>
<li class="item-inactive"><a href="link3.html">third item</a></li>
<li class="item-1"><a href="link4.html">fourth item</a></li>
<li class="item-0"><a href="link5.html">fifth item</a>
</li></ul>
</div>
</body></html>
经过处理后, li 节点标签被补全,并且还⾃动添加了 body、 html 节点。还可以直接读取⽂本⽂件进⾏解析:
from lxml import etree
html = etree.parse('./test.html', etree.HTMLParser())
result = etree.tostring(html)
print(result.decode('utf-8'))
test.html 的内容就是上⾯例⼦的 HTML 代码,内容如下:
<div>
<ul>
<li class="item-0"><a href="link1.html">first item</a></li>
<li class="item-1"><a href="link2.html">second item</a></li>
<li class="item-inactive"><a href="link3.html">third item</a></li>
<li class="item-1"><a href="link4.html">fourth item</a></li>
<li class="item-0"><a href="link5.html">fifth item</a>
</ul>
</div>
这次输出结果略有不同,多了⼀个DOCTYPE 声明,不过对解析没有任何影响,结果如下:
<html><body><div>
<ul>
<li class="item-0"><a href="link1.html">first item</a></li>
<li class="item-1"><a href="link2.html">second item</a></li>
<li class="item-inactive"><a href="link3.html">third item</a></li>
<li class="item-1"><a href="link4.html">fourth item</a></li>
<li class="item-0"><a href="link5.html">fifth item</a>
</li></ul>
</div></body></html>
在python中使⽤xpath
from lxml import etree
# 第⼀种⽅式,直接在python代码中解析html字符串
text = """ <div> <ul> <li class="item-0"><a href="link1.html">first item</a></li> .... </ul> </div> """
resp_html = etree.HTML(text)
#第⼆种⽅式,读取⼀个html⽂件并解析
html = etree.parse('./test.html', etree.HTMLParser())
result = etree.tostring(html)
print(result.decode('utf-8'))
5、所有节点
⽤以 // 开头的 XPath 规则来选取所有符合要求的节点:
from lxml import etree
html = etree.parse('./test.html', etree.HTMLParser())
result = html.xpath('//*')
print(result)
# 运⾏结果
""" [<Element html at 0x1d6610ebe08>, <Element body at 0x1d6610ebf08>, <Element div at 0x1d6610ebf48>, <Element ul at 0x1d6610ebf88>, <Element li at 0x1d6610ebfc8>, <Element a at 0x1d661115088>, <Element li at 0x1d6611150c8>, <Element a at 0x1d661115108>, <Element li at 0x1d661115148>, <Element a at 0x1d661115048>, <Element li at 0x1d661115188>, <Element a at 0x1d6611151c8>, <Element li at 0x1d661115208>, <Element a at 0x1d661115248>] """
- 代表匹配所有节点,返回的结果是⼀个列表,每个元素都是⼀个 Element 类型,后跟节点名称。
也可以指定匹配的节点名称:
from lxml import etree
html = etree.parse('./test.html', etree.HTMLParser())
result = html.xpath('//li')
print(result)
# 运⾏结果
[<Element li at 0x23fb219af08>, <Element li at 0x23fb219af48>, <Element li at
0x23fb219af88>,
<Element li at 0x23fb219afc8>, <Element li at 0x23fb21c5048>]
<Element li at 0x23fb219af08>
取出其中某个对象时可以直接⽤索引。
6、子节点
通过 / 或 // 即可查找元素的⼦节点或⼦孙节点。选择 li 节点的所有直接 a ⼦节点:
from lxml import etree
html = etree.parse('.test.html', etree.HTMLParser())
result = html.xpath('//li/a')
print(result)
此处的 / ⽤来获取直接⼦节点,如果要获取所有⼦孙节点,将 / 换成 // 即可。
7、父节点
知道⼦节点,查询⽗节点可以⽤ … 来实现:
# 获得 href 属性为 link4.html 的 a 节点的⽗节点的 class 属性
# ⽅法⼀
from lxml import etree
html = etree.parse('./test.html', etree.HTMLParser())
result = html.xpath('//a[@href="link4.html"]/../@class')
print(result)
# ⽅法⼆
from lxml import etree
html = etree.parse('./test.html', etree.HTMLParser())
result = html.xpath('//a[@href="link4.html"]/parent::*/@class')
print(result)
# 运⾏结果: ['item-1']
8、属性匹配
匹配时可以⽤@符号进⾏属性过滤:
from lxml import etree
html = etree.parse('./test.html', etree.HTMLParser())
result = html.xpath('//li[@class="item-inactive"]')
print(result)
# 运⾏结果: [<Element li at 0x2089793a3c8>]
9、文本获取
有两种⽅法:⼀是获取⽂本所在节点后直接获取⽂本,⼆是使⽤ //。
# 第⼀种
from lxml import etree
html = etree.parse('./test.html', etree.HTMLParser())
result = html.xpath('//li[@class="item-0"]/a/text()')
print(result)
# 第⼆种
from lxml import etree
html = etree.parse('./test.html', etree.HTMLParser())
result = html.xpath('//li[@class="item-0"]//text()')
print(result)
第⼆种⽅法会获取到补全代码时换⾏产⽣的特殊字符,推荐使⽤第⼀种⽅法,可以保证获取的结果是整洁的。
10、属性获取
在xpath语法中,@符号相当于过滤器,可以直接获取节点的属性值:
from lxml import etree
html = etree.parse('./test.html', etree.HTMLParser())
result = html.xpath('//li/a/@href')
print(result)
# 运⾏结果: ['link1.html', 'link2.html', 'link3.html', 'link4.html',
'link5.html']
11、属性多值匹配
有时候,某些节点的某个属性可能有多个值:
from lxml import etree
text = ''' <li class="li li-first"><a href="link.html">first item</a></li> '''
html = etree.HTML(text)
result = html.xpath('//li[contains(@class, "li")]/a/text()')
print(result)
# 运⾏结果: ['first item']
12、多属性匹配
当前节点有多个属性时,需要同时进行匹配:
from lxml import etree
text = ''' <li class="li li-first" name="item"><a href="link.html">first item</a></li> '''
html = etree.HTML(text)
result = html.xpath('//li[contains(@class, "li") and @name="item"]/a/text()')
print(result)
# 运⾏结果: ['first item']
扩展:XPath运算符
13、按序选择
匹配结果有多个节点,需要选中第二个或者最后一个,可以按照中括号内加索引或其他相应语法获得:
from lxml import etree
text = ''' <div> <ul> <li class="item-0"><a href="link1.html">first item</a></li> <li class="item-1"><a href="link2.html">second item</a></li> <li class="item-inactive"><a href="link3.html">third item</a></li> <li class="item-1"><a href="link4.html">fourth item</a></li> <li class="item-0"><a href="link5.html">fifth item</a> </ul> </div> '''
html = etree.HTML(text)
# 获取第⼀个
result = html.xpath('//li[1]/a/text()')
print(result)
# 获取最后⼀个
result = html.xpath('//li[last()]/a/text()')
print(result)
# 获取前两个
result = html.xpath('//li[position()<3]/a/text()')
print(result)
# 获取倒数第三个
result = html.xpath('//li[last()-2]/a/text()')
print(result)
""" 运⾏结果: ['first item'] ['fifth item'] ['first item', 'second item'] ['third item'] """
XPath 中提供了100多个函数,包括存取、数值、逻辑、节点、序列等处理功能,具体作⽤可以参考: http://www.w3school.com.cn/xpath/xpath_functions.asp
14、节点轴选择
XPath提供了很多节点轴选择方法,包括子元素,父元素,祖先元素等:
from lxml import etree
text = ''' <div> <ul> <li class="item-0"><a href="link1.html"><span>first item</span></a></li> <li class="item-1"><a href="link2.html">second item</a></li> <li class="item-inactive"><a href="link3.html">third item</a></li> <li class="item-1"><a href="link4.html">fourth item</a></li> <li class="item-0"><a href="link5.html">fifth item</a> </ul> </div> '''
html = etree.HTML(text)
# 获取所有祖先节点
result = html.xpath('//li[1]/ancestor::*')
print(result)
# 获取 div 祖先节点
result = html.xpath('//li[1]/ancestor::div')
print(result)
# 获取当前节点所有属性值
result = html.xpath('//li[1]/attribute::*')
print(result)
# 获取 href 属性值为 link1.html 的直接⼦节点
result = html.xpath('//li[1]/child::a[@href="link1.html"]')
print(result)
# 获取所有的的⼦孙节点中包含 span 节点但不包含 a 节点
result = html.xpath('//li[1]/descendant::span')
print(result)
# 获取当前所有节点之后的第⼆个节点
result = html.xpath('//li[1]/following::*[2]')
print(result)
# 获取当前节点之后的所有同级节点
result = html.xpath('//li[1]/following-sibling::*')
print(result)
""" [<Element html at 0x231a8965388>, <Element body at 0x231a8965308>, <Element div at 0x231a89652c8>, <Element ul at 0x231a89653c8>] [<Element div at 0x231a89652c8>] ['item-0'] [<Element a at 0x231a89653c8>] [<Element span at 0x231a89652c8>] [<Element a at 0x231a89653c8>] [<Element li at 0x231a8965308>, <Element li at 0x231a8965408>, <Element li at 0x231a8965448>, <Element li at 0x231a8965488>] """
更多参考文档:轴的用法: http://www.w3school.com.cn/xpath/xpath_axes.asp XPath 的⽤法: http://www.w3school.com.cn/xpath/index.asp Python lxml 的⽤法: http://lxml.de
边栏推荐
- 测试人的职场危机是35岁?不是,而是中年被裁!
- 主从复制读写分离保姆级教学
- DIY a cache
- 接口测试与接口测试自动化
- Data storage and disaster recovery (2nd Edition) editor in chief Lu Xianzhi Wu Chunling comprehensive training answer
- TCP协议详解
- 3、 Experimental report on the implementation of SMB sharing and FTP construction by freenas
- In 2 years, the salary increased by 20K, and the transformation from outsourcing manual to test manager
- Code quality inspection based on sonarqube
- 自动备份MySQL。且保留7天案例
猜你喜欢

太香了, 终于明白为什么这么多人要转行软件测试了~

Volatile final explanation

Attack and defense World Web

socket详解

appium中控件坐标及控件属性获取

软件测试如何自学?【从0到1超全面解析】(附学习笔记)

主从复制读写分离保姆级教学

In 2 years, the salary increased by 20K, and the transformation from outsourcing manual to test manager

POI framework learning - Import and export cases

The experience of finding a job after coming out of the software testing training class taught me these five things
随机推荐
头文件ctype.h(详细)
The experience of finding a job after coming out of the software testing training class taught me these five things
无重叠区间
Desired in appium_ Caps parameter record
Five years' experience: the monthly salary is 3000 to 30000, and the change of Test Engineers
Edge calculation kubeedge+edgemash
"Finally I left bytek..." confession of a test engineer with an annual salary of 40W
Alipay computer website payment
Pytest series-01-installation and introduction
“终于我从字节离职了...“一个年薪40W的测试工程师的自白..
Decompose a number into the form of adding multiple addends
After 3 months of job hunting, most resumes are dead in the sea. When it comes to manual testing, they shake their heads again and again ~ it's too difficult
mysql基础相关(重要)
On the meaning of XML file format in the framework
2-3树 B树 b+树
to flash back
MySQL foundation related (important)
Principle and configuration of static routing
都说软件测试有手就行,每个人都能做,但为何每年仍有大批被劝退的?
网络层协议