python爬虫学习29
五、Xpath的使用其四
5-11 多属性匹配
在之前我们学习了如何匹配一个拥有多值属性的节点,那么如何匹配拥有多个属性的节点呢?
这就要用到运算符
例如,我们稍稍修改一下这里的html节点

现在我们想要匹配那个同时拥有class与name节点下的a节点的内容:
from lxml import etree
html = etree.parse('./python.html', etree.HTMLParser())
result = html.xpath('//li[contains(@class,"li") and @name="item"]/a/text()')
print(result)
运行结果:可以看到意见反馈被我们提取出来了

Xpath中的运算符

5-12 按序选择
像是之前我们获取节点时返回了许多符合的结果,若是我们想要点用其中的某一个或是第几个就要进行如下操作:
例如:还是这里的三个节点

from lxml import etree
html = etree.parse('./python.html', etree.HTMLParser())
result0 = html.xpath('//li[1]/a/text()')
print(result0)
result1 = html.xpath('//li[last()]/a/text()')
print(result1)
result2 = html.xpath('//li[position()<=2]/a/text()')
print(result2)
result3 = html.xpath('//li[last()-1]/a/text()')
print(result3)
result = html.xpath('//li/a/text()')
print(result)
运行结果:

5-14 节点轴选择
一些常用的关于节点轴的调用方法:
from lxml import etree as e
html = e.parse('./python.html', e.HTMLParser())
result = html.xpath('//li[1]/ancestor::*')
print(result)
result = html.xpath('//li[1]/ancestor::div')
print(result)
result = html.xpath('//li[1]/attribute::*')
print(result)
result = html.xpath('//li[1]/child::a[@target="_blank"]')
print(result)
result = html.xpath('//ul[1]/descendant::a')
print(result)
result = html.xpath('//ul[1]/following::*')
print(result)
result = html.xpath('//li[1]/following-sibling::*')
print(result)
运行结果:

至此我们就已经基本掌握了Xpath的使用方法
今日结束,未完待续!
|