米琪卡哇伊
看下面一些例子:1)获取子节点:getchildren()等价于child::*>>>doc.getchildren()2)获取当前节点:"."等价于self::node()>>>doc.xpath(".")>>>doc.xpath("self::node()")3)获取父节点:".."等价于parent::node()>>>doc.head.xpath("..")>>>doc.head.xpath("parent::node()")4)ancestor轴和descendant轴分别代表当前元素所有祖先元素、所有后代元素,比如:>>>meta.xpath('ancestor::*')>>>meta.xpath('ancestor::head')>>>doc.xpath('descendant::table')>>>doc.xpath('descendant::table[@id="tcdatafields"]')>>>doc.xpath('//table[@id="tcdatafields"]')5)ancestor-or-self和descendant-or-self轴分别表示当前元素或其所有祖先元素、当前元素或其所有后代元素,比如:>>>meta.xpath('ancestor-or-self::*'),,]6)child和parent轴分别表示当前元素所有子元素、父元素:>>>doc.xpath('child::head')>>>head.xpath('child::meta[1]')>>>head.xpath('child::meta[position()<3]')7)attribute轴表示当前元素的所有属性,例如下面是meta元素的name和content两个属性以及取值:>>>meta.items()[('name','googlebot'),('content','index,follow')]获取所有属性取值:>>>meta.xpath('attribute::*')['googlebot','index,follow']获取name属性的取值:>>>meta.xpath('attribute::name')['googlebot']8)following和preceding分别表示当前元素的所有后继元素、前置元素,比如:>>>meta.xpath('following::*')>>>meta.xpath('preceding::*')9)following-sibling和preceding-sibling轴分别表示当前元素的所有平级后继元素、平级前置元素,比如:>>>meta.xpath('preceding-sibling::*')>>>meta.xpath('following-sibling::*')10)self轴表示当前元素自身>>>doc.xpath("self::*")使用谓词(predicates)谓词就是step中使用中括号[...]定义的那部分,使用谓词能实现精确查找,看下面的例子:>>>doc.xpath('/html/head/meta'),,,,,,]1)位置谓词>>>doc.xpath('/html/head/meta[1]')>>>doc.xpath('/html/head/meta[2]')>>>doc.xpath('/html/head/meta[last()]')>>>doc.xpath('/html/head/meta[last()-1]')>>>doc.xpath('/html/head/meta[position()<3]')注:这里使用了last()和position()两个函数,xpath还支持更多的函数,结合这些函数可以获得非常强大的处理能力。2)属性谓词含有属性name的meta元素:>>>doc.xpath('/html/head/meta[@name]'),,,]含有属性name而且其取值为robots的meta元素:含有任意属性的meta元素:>>>doc.xpath('/html/head/meta[@*]')3)函数谓词xpath内置很多函数,灵活使用这些函数,可以极大提升查找效率,比如:-使用text()函数>>>doc.xpath('//td[text()="2017-03-21"]')-使用contains函数>>>[td.textfortdindoc.xpath('//td[contains(text(),"2017-03-2")]')]['2017-03-29','2017-03-28','2017-03-27','2017-03-24','2017-03-23','2017-03-22','2017-03-21','2017-03-20']-使用starts-with函数>>>[td.textfortdindoc.xpath('//td[starts-with(text(),"2017-02-2")]')]['2017-02-28','2017-02-27','2017-02-24','2017-02-23','2017-02-22','2017-02-21','2017-02-20']>>>[td.textfortdindoc.xpath('//td[text()>21.0andtext()<23.0]')]['21.02']>>>[td.textfortdindoc.xpath('//td[text()21.0]')]['21.02','-2.64']通配符xpath也支持通配符"*",其中'*"可以匹配任何标签元素,"@*"可以匹配任何元素属性,node()可以匹配任何节点:>>>head.xpath('./*'),,,,,,,,,]>>>head.xpath('./meta[@*]')>>>head.xpath('./node()')