[Crawler] Advanced usage of Xpath

The speed of xpath is relatively fast, which is the better choice for crawlers in web page positioning, but many front-end codes of web pages are confusing and difficult to locate, and it is not easy to learn positioning (mainly because there are few comprehensive tutorials). Here are a few points that may be useful in the programming process. things, welcome to learn together, criticize and correct.
Test environment: Python environment, lxml.etree

  • The html code used in the experiment
<!DOCTYPE html>
<html>
<head>
    <title>xpath test</title>
</head>
<body>
<div price="99.8">
    <div>
        <ul>
            <li>Time</li>
            <li> Point </ li>
            <li>Tasks</li>
        </ul>
    </div>
    <div id='testid' data-h="first">
        <h2>Here is a subtitle</h2>
        <ol>
            <li data="one">1</li>
            <li data="two">2</li>
            <li data="three">3</li>
        </ol>
        <ul>
            <li code="84">84</li>
            <li code="104">104</li>
            <li code="223">223</li>
        </ul>
    </div>
    <div>
        <h3> Here is the content of H3
             <a href= " http://www.baidu.com " > Baidu </a>
            <ul>
                <li>test1</li>
                <li>test2</li>
            </ul>
        </h3>
    </div>
    <div id="go">
        <ul>
            <li>1</li>
            <li>2</li>
            <li>3</li>
            <li>4</li>
            <li>5</li>
            <li>6</li>
            <li>7</li>
            <li>8</li>
            <li>9</li>
            <li>10</li>
        </ul>
    </div>
</div>
</body>
</html>

 

1. Match all items under a node.//

//Get all the matching nodes in the document, .get the current node, sometimes we need to get all the nodes under the current node, .//must be used in combination ., //otherwise the matching results of the entire document will be obtained.

2. Match all attribute values ​​that contain an attribute//@lang

print tree.xpath( ' //@code ' ) #Matches all attribute values ​​with code attributes 
>>[ ' 84 ' , ' 104 ' , ' 223 ' ]

 

3. Select several paths|

This symbol is used to write multiple expressions in an xpath, |separate them, and each expression does not interfere with each other

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::*当前节点的所有子元素
>>[<Element h2 at 0x21bd148>, <Element ol at 0x21bd108>, <Element ul at 0x21bd0c8>]

>>#定位某节点下为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元素
>>[<Element div at 0x23fc108>]
>>[<Element div at 0x23fc108>, <Element div at 0x23fc0c8>]

 

  • descendant:后代 / descendant-or-self:后代及当前节点本身

使用方法同上

  • following :选取文档中当前节点的结束标签之后的所有节点
#定位testid之后不包含id属性的div标签下所有的li中第一个li的text属性
>>print tree.xpath('//div[@id="testid"]/following::div[not(@id)]/.//li[1]/text()') 
>>['test1']

 

  • namespace:选取当前节点的所有命名空间节点
>>print tree.xpath('//div[@id="testid"]/namespace::*') #选取命名空间节点
>>[('xml', 'http://www.w3.org/XML/1998/namespace')]

 

  • parent:选取当前节点的父节点
>>#选取data值为one的父节点的子节点中最后一个节点的值
>>print tree.xpath('//li[@data="one"]/parent::ol/li[last()]/text()') 
>>['3']
>>#注意这里的用法,parent::父节点的名字

 

  • preceding:选取文档中当前节点的开始标签之前的所有节点
>>#记住是标签开始之前,同级前节点及其子节点
>>print tree.xpath('//div[@id="testid"]/preceding::div/ul/li[1]/text()')[0] 
>>时间
>>#下面这两条可以看到其顺序是靠近testid节点的优先
>>print tree.xpath('//div[@id="testid"]/preceding::li[1]/text()')[0]
>>print tree.xpath('//div[@id="testid"]/preceding::li[3]/text()')[0]
>>任务
>>时间

 

  • preceding-sibling:选取当前节点之前的所有同级节点
>>#记住只能是同级节点
>>print tree.xpath('//div[@id="testid"]/preceding-sibling::div/ul/li[2]/text()')[0]
>>print tree.xpath('//div[@id="testid"]/preceding-sibling::li') #这里返回的就是空的了
>>地点
>>[]

 

  • self:选取当前节点
>>#选取带id属性值的div中包含data-h属性的标签的所有属性值
>>print tree.xpath('//div[@id]/self::div[@data-h]/attribute::*') 
>>['testid', 'first']

 

  • 组合拳
#定位id值为testid下的ol下的li属性值data为two的父元素ol的兄弟前节点h2的text值
>>print tree.xpath('//*[@id="testid"]/ol/li[@data="two"]/parent::ol/preceding-sibling::h2/text()')[0] 
>>这里是个小标题

 

5、position定位

>>print tree.xpath('//*[@id="testid"]/ol/li[position()=2]/text()')[0] 
>>2

 

6、条件

>>定位所有h2标签中text值为`这里是个小标题`
>>print tree.xpath(u'//h2[text()="这里是个小标题"]/text()')[0]
>>这里是个小标题

 

7、函数

  • count:统计
>>print tree.xpath('count(//li[@data])') #节点统计
>>3.0

 

  • concat:字符串连接
>>print tree.xpath('concat(//li[@data="one"]/text(),//li[@data="three"]/text())')
>>13

 

  • string:解析当前节点下的字符
>>#string只能解析匹配到的第一个节点下的值,也就是作用于list时只匹配第一个
>>print tree.xpath('string(//li)') 
>>时间

 

  • local-name:解析节点名称
>>print tree.xpath('local-name(//*[@id="testid"])') #local-name解析节点名称
>>div

 

  • contains(string1,string2):如果 string1 包含 string2,则返回 true,否则返回 false
>>tree.xpath('//h3[contains(text(),"H3")]/a/text()')[0] #使用字符内容来辅助定位
>>百度一下

>>一记组合拳
>>#匹配带有href属性的a标签的先辈节点中的div,其兄弟节点中前一个div节点下ul下li中text属性包含“务”字的节点的值
>>print tree.xpath(u'//a[@href]/ancestor::div/preceding::div/ul/li[contains(text(),"务")]/text()')[0] 
>>任务

 

  • not:布尔值(否)
>>print tree.xpath('count(//li[not(@data)])') #不包含data属性的li标签统计
>>18.0

 

  • string-length:返回指定字符串的长度
>>#string-length函数+local-name函数定位节点名长度小于2的元素
>>print tree.xpath('//*[string-length(local-name())<2]/text()')[0] 
>>百度一下

 

  • 组合拳2
>>#contains函数+local-name函数定位节点名包含di的元素
>>print tree.xpath('//div[@id="testid"]/following::div[contains(local-name(),"di")]') 
>>[<Element div at 0x225e108>, <Element div at 0x225e0c8>]

 

  • or:多条件匹配
>>print tree.xpath('//li[@data="one" or @code="84"]/text()') #or匹配多个条件
>>['1', '84']
>>#也可使用|
>>print tree.xpath('//li[@data="one"]/text() | //li[@code="84"]/text()') #|匹配多个条件
>>['1', '84']

 

  • 组合拳3:floor + div除法 + ceiling
>>#position定位+last+div除法,选取中间两个
>>tree.xpath('//div[@id="go"]/ul/li[position()=floor(last() div 2+0.5) or position()=ceiling(last() div 2+0.5)]/text()') 
>>['5', '6']

 

  • 组合拳4隔行定位:position+mod取余
>>#position+取余运算隔行定位
>>tree.xpath('//div[@id="go"]/ul/li[position()=((position() mod 2)=0)]/text()') 

 

  • starts-with:以。。开始
>>#starts-with定位属性值以8开头的li元素
>>print tree.xpath('//li[starts-with(@code,"8")]/text()')[0]
>>84

 

  • div:对某两个节点的属性值做除法
>>print tree.xpath('//div[@id="testid"]/ul/li[3]/@code div //div[@id="testid"]/ul/li[1]/@code')
>>2.65476190476

 

  • 组合拳4:根据节点下的某一节点数量定位
>>#选取所有ul下li节点数大于5的ul节点
>>print tree.xpath('//ul[count(li)>5]/li/text()')
>>['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']

 

9、将对象还原为字符串

>>> s = tree.xpath('//*[@id="testid"]')[0] #使用xpath定位一个节点
>>> s
<Element div at 0x2b6ffc8>
>>> s2 = etree.tostring(s) #还原这个对象为html字符串
>>> s2
'<div id="testid">\n\t\t<h2>&#213;&#226;&#192;&#239;&#202;&#199;&#184;&#246;&#208;&#161;&#177;&#234;&#204;&#226;</h2>\n\t\t<ol>\n\t\t\t<li data="one">1</li>\n\t\t\t<li data="two">2</li>\n\t\t\t<li data="three">3</li>\n\t\t</ol>\n\t\t<ul>\n\t\t\t<li code="84">84</li>\n\t\t\t<li code="104">104</li>\n\t\t\t<li code="223">223</li>\n\t\t</ul>\n\t</div>\n\t'

10、选取一个属性中的多个值
举例:<div class="mp-city-list-container mp-privince-city" mp-role="provinceCityList">
选择这个div的方案网上有说用and的,但是似乎只能针对不同的属性的单个值
本次使用contains
>>.xpath('div[contains(@class,"mp-city-list-container mp-privince-city")]')
>>当然也可以直接选取其属性的第二个值
>>.xpath('div[contains(@class,"mp-privince-city")]')
>>重点是class需要添加一个@符号
本次验证否定了网上的and,使用了contains,验证环境在scrapy的response.xpath下

 

说明一点,xpath虽快,但是使用时尽量使用简洁高效的方式,本文旨在定位那些较难的地方使用,刻意追求晦涩难懂的技巧会影响其效率,并不可取。

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325149011&siteId=291194637