python爬虫利器之xpath_Python爬虫解析库之Xpath高级用法

xpath速度比较快,是爬虫在网页定位中的较优选择,但是很多网页前端代码混乱难以定位,而学习定位也较为不易,这里列出一点编程过程中可能有用的东西。

试验环境:Python环境,lxml.etree

试验所使用的html代码html>

xpath test
  • 时间
  • 地点
  • 任务

这里是个小标题

  1. 1
  2. 2
  3. 3
  • 84
  • 104
  • 223

这里是H3的内容

百度一下

  • test1
  • test2
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

1、匹配某节点下的所有.//

//获取文档中所有匹配的节点,.获取当前节点,有的时候我们需要获取当前节点下的所有节点,.//一定要结合.使用//,否则都会获取整个文档的匹配结果.

2、匹配包含某属性的所有的属性值//@langprint tree.xpath('//@code') #匹配所有带有code属性的属性值

>>['84', '104', '223']

3、选取若干路径|

这个符号用于在一个xpath中写多个表达式用,用|分开,每个表达式互不干扰print tree.xpath('//div[@id="testid"]/h2/text() | //li[@data]/text()') #多个匹配条件

>>[u'\u8fd9\u91cc\u662f\u4e2a\u5c0f\u6807\u9898', '1', '2', '3']

4、 Axes(轴)

child:选取当前节点的所有子元素>>print tree.xpath('//div[@id="testid"]/child::ul/li/text()') #child子节点定位

>>['84', '104', '223']

>>print tree.xpath('//div[@id="testid"]/child::*') #child::*当前节点的所有子元素

>>[, , ]

>>#定位某节点下为ol的子节点下的所有节点

>>print tree.xpath('//div[@id="testid"]/child::ol/child::*/text()')

>>['1', '2', '3']

attribute:选取当前节点的所有属性>>print tree.xpath('//div/attribute::id') #attribute定位id属性值

>>['testid', 'go']

>>print tree.xpath('//div[@id="testid"]/attribute::*') #定位当前节点的所有属性

>>['testid', 'first']

ancestor:父辈元素 / ancestor-or-self:父辈元素及当前元素>>print tree.xpath('//div[@id="testid"]/ancestor::div/@price') #定位父辈div元素的price属性

>>['99.8']

>>print tree.xpath('//div[@id="testid"]/ancestor::div') #所有父辈div元素

>>print tree.xpath('//div[@id="testid"]/ancestor-or-self::div') #所有父辈及当前节点div元素

>>[]

>>[, ]

following :选取文档中当前节点的结束标签之后的所有节点#定位testid之后不包含id属性的div标签下所有的li中第一个li的text属性

>>print tree.xpath('//div[@id="testid"]/following::div[not(@id)]/.//li[1]/text()')

>>['test1']

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值