gpt4 book ai didi

python - 在列表中查找节点的编号(位置)

转载 作者:太空宇宙 更新时间:2023-11-03 11:25:37 25 4
gpt4 key购买 nike

在 xpath 中我如何找到哪个数字(取决于从哪里开始,0 或 1,c 是 2 或 3)例如项目 c以下列表:

<ol>
<li>a</li>
<li>b</li>
<li>c</li>
<li>d</li>
</ol>

最佳答案

您可以使用 XPathcount 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

关于python - 在列表中查找节点的编号(位置),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34594630/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com