xpath sequential selection

Sometimes when we select certain attributes may match multiple nodes simultaneously, but we only want one of these nodes, such as the second node, or the last node, then how to do it?

In this case the brackets can be passed by the method of obtaining the index of the node-specific order, for example:

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.HTML(text)
result = html.xpath('//li[1]/a/text()')
print(result)
result = html.xpath('//li[last()]/a/text()')
print(result)
result = html.xpath('//li[position()<3]/a/text()')
print(result)
result = html.xpath('//li[last()-2]/a/text()')
print(result)

The first choice that we choose the first li node, incoming numbers in parentheses 1 can be, and pay attention to where the code is different, No. 1 is the beginning, not the beginning of zero.

Second choice we choose the last li node, in parentheses passed last () to return to the node is the last li.

We selected third node li selected position is less than 3, that is, the result of position number 1 and the node 2, is obtained before the two nodes li.

The fourth choice we selected third last li nodes in parentheses passed last () - 2 can be, because the last () is the last one, the last () - 2 is the last third.

Results are as follows:

['first item']
['fifth item']
['first item', 'second item']
['third item']

Here we use the last (), position () function and the like, XPath 100 are provided a plurality of functions, including access processing function, numeric, string, logical nodes, and a sequence.
Specific reference may effect all functions: http://www.w3school.com.cn/xpath/xpath_functions.asp .

Guess you like

Origin www.cnblogs.com/hankleo/p/11227266.html