首页 > 其他 > 详细

xpath使用详解

时间:2020-02-14 14:23:21      阅读:62      评论:0      收藏:0      [点我收藏+]

1XPath简介

  说明

XPath语法

from lxml import etree

text = ‘‘‘
div>
<ul>
<li class="item-0"><a href="https://ask.hellobi.com/link1.html">first item</a></li>
<li class="item-1"><a href="https://ask.hellobi.com/link2.html">second item</a></li>
<li class="item-inactive"><a href="https://ask.hellobi.com/link3.html">third item</a></li>
<li class="item-1"><a href="https://ask.hellobi.com/link4.html">fourth item</a></li>
<li class="item-0"><a href="https://ask.hellobi.com/link5.html">fifth item</a>
</ul>
</div>
‘‘‘

html = etree.parse("./test.html", etree.HTMLParser())
result = etree.tostring(html)
print(result.decode(‘utf-8‘))

# 获取所有节点
# * 代表匹配所有节点,也就是整个HTML文本中所有节点都会被获取,
result = html.xpath(‘//*‘)
print(result)

# 选择指定节点名称, 获取所有li节点 以列表形式返回结果
result = html.xpath(‘//li‘)
print(result)
# 取出其中一个对象直接用中括号加索引直接取出,[0]
print(result[0])

# 子节点
# 选取li节点所有直接a子节点
# //li是选中所有li节点 /a是选中li节点所有直接子节点a,
# 二者组合在一起即获取了所有li节点的所有a子节点
result = html.xpath(‘//li/a‘)
print(result)

# 父节点
# ..获取父节点
result = html.xpath(‘//a[@href="https://ask.hellobi.com/link2.html"]/../@class‘)
print(result)

# 使用parent:: 获取父节点
result = html.xpath(‘//a[@href="https://ask.hellobi.com/link2.html"]/parent::*/@class‘)
print(result)

# 属性匹配
# 用@符号进行属性过滤,
result = html.xpath(‘//li[@class="item-1"]‘)
print(result)

# 文本获取
# 利用text()方法可以获取节点中的文本,
result = html.xpath(‘//li[@class="item-0"]/text()‘)
print(result)
# 没有获取任何文本,在xpath中text()前面是/,而 /的含义是选取直接子节点
# 而此处 li的直接子节点都是a节点,文本都在a节点内部
# 如果我们想获取li节点内部的文本有两种方式
# 一种是选取到a节点再获取文本
# 另一种使用 //
result = html.xpath(‘//li[@class="item-1"]/a/text()‘)
print(result)
result = html.xpath(‘//li[@class="item-1"]//text()‘)
print(result)

# 属性获取
# @ 获取节点属性
result = html.xpath(‘//li/a/@href‘)
print(result)

# 属性多值匹配
# 如果属性有多个值用 contains()
result = html.xpath(‘//li[contains(@class,"item")]/a/text()‘)
print(result)

# 按序选择
# 某些属性同时匹配了多个节点,我们只想要其中的某个节点,
# 可以利用[] 传入索引的方法获取特定序列的节点
# 获取第一个li节点,中括号中传入数字1即可 这里序号是以1开始 而不是0
result = html.xpath(‘//li[1]/a/text()‘)
print(result)
# 获取最后一个li节点
result = html.xpath(‘//li[last()]/a/text()‘)
print(result)
# 获取位置小于3的节点
result = html.xpath(‘//li[position()<3]/a/text()‘)
print(result)

# 节点轴选择
#获取所有祖先节点
result = html.xpath(‘//li[1]/ancestor::*‘)
print(result)
# 获取所有子节点
result = html.xpath(‘//li[1]/child::*/text()‘)
print(result)

xpath使用详解

原文:https://www.cnblogs.com/-fengmu/p/12306794.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!