美文网首页
[Python] XPath使用

[Python] XPath使用

作者: 半为花间酒 | 来源:发表于2020-05-09 22:06 被阅读0次

内容参考:4.1-使用XPath(崔庆才)
官方文档:http://pyquery.readthedocs.io
更多XPath的用法:http://www.w3school.com.cn/xpath/index.asp
更多Python lxml库的用法: http://lxml.de/

内容是以前的学习笔记,内容不全,主观性较大,部分基础知识未展示

Xpath

XPath的选择功能十分强大,它提供了非常简洁明了的路径选择表达式。另外,它还提供了超过100个内建函数,用于字符串、数值、时间的匹配以及节点、序列的处理等。几乎所有我们想要定位的节点,都可以用XPath来选择

XPath于1999年11月16日成为W3C标准,它被设计为供XSLT、XPointer以及其他XML解析软件使用,更多的文档可以访问其官方网站:https://www.w3.org/TR/xpath/

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>
'''

1. 多值匹配 / 多属性匹配

from lxml import html
text = '''
<li class="li li-first" name="item"><a href="link.html">first item</a></li>
'''

selector = html.fromstring(text)
results = selector.xpath('//li[contains(@class, "li") and @name="item"]/a/text()')
print(results)

2. 专向选择节点

html = html.fromstring(text)

# 选择最后一个
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)

3. 节点轴选择

from lxml import html

html = html.fromstring(text)
# 调用了ancestor轴,可以获取所有祖先节点。其后需要跟两个冒号,然后是节点的选择器,直接使用*,表示匹配所有节点
result = html.xpath('//li[1]/ancestor::*')
print(result)

# 只有div这个祖先节点
result = html.xpath('//li[1]/ancestor::div')
print(result)

# 父节点
result = html.xpath('//a[@href="link4.html"]/parent::*/@class')
print(result)

# 调用了attribute轴,可以获取所有属性值,其后跟的选择器是*,这代表获取节点的所有属性
result = html.xpath('//li[1]/attribute::*')
print(result)

# 调用了child轴,可以获取所有直接子节点。加了限定条件,选取href属性为link1.html的a节点
result = html.xpath('//li[1]/child::a[@href="link1.html"]')
print(result)

# 调用了descendant轴,可以获取所有子孙节点。这里我们又加了限定条件获取span节点
result = html.xpath('//li[1]/descendant::span')
print(result)

# 调用了following轴,可以获取当前节点之后的所有节点。虽然使用的是*匹配,但又加了索引选择,所以只获取了第二个后续节点
result = html.xpath('//li[1]/following::*[2]')
print(result)

# 调用了following-sibling轴,可以获取当前节点之后的所有同级节点。使用*匹配,所以获取了所有后续同级节点
result = html.xpath('//li[1]/following-sibling::*')
print(result)

相关文章

网友评论

      本文标题:[Python] XPath使用

      本文链接:https://www.haomeiwen.com/subject/lbzlnhtx.html