在xpath中,我如何找到哪个数字(取决于哪里,0或1,你开始, c 是2或3)是例如项目 c in以下列表:
<ol>
<li>a</li>
<li>b</li>
<li>c</li>
<li>d</li>
</ol>
答案 0 :(得分:2)
您可以使用XPath和count the preceding li
siblings:
count(//ol/li[. = 'c']/preceding-sibling::*)
演示(使用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