In xpath how can I find which number (depending on where, 0 or 1, you start, c is either 2 or 3) is for example item c in the following list:
<ol>
<li>a</li>
<li>b</li>
<li>c</li>
<li>d</li>
</ol>
In xpath how can I find which number (depending on where, 0 or 1, you start, c is either 2 or 3) is for example item c in the following list:
<ol>
<li>a</li>
<li>b</li>
<li>c</li>
<li>d</li>
</ol>
You can use XPath and count the preceding li
siblings:
count(//ol/li[. = 'c']/preceding-sibling::*)
Demo (using lxml.etree
):
>>> from lxml import etree as ET
>>> data = """
... <ol>
... <li>a</li>
... <li>b</li>
... <li>c</li>
... <li>d</li>
... </ol>
... """
>>> tree = ET.fromstring(data)
>>> value = "c"
>>> int(tree.xpath("count(//ol/li[. = '%s']/preceding-sibling::li)" % value))
2