一定有更简单的方法来做到这一点。我需要大量 html 文档中的一些文本。在我的测试中,找到它的最可靠方法是在 div 元素的 text_content 中查找特定单词。如果我想检查包含我的文本的元素上方的特定元素,我一直在枚举我的 div 元素列表并使用包含我的文本的元素的索引,然后通过对索引进行操作来指定前一个元素。但我相信一定有更好的方法。我似乎无法弄清楚。
如果不清楚
for pair in enumerate(list_of_elements):
if 'the string' in pair[1].text_content():
thelocation=pair[0]
the_other_text=list_of_elements[thelocation-9].text_content()
或
theitem.getprevious().getprevious().getprevious().getprevious().getprevious().getprevious().getprevious().getprevious().getprevious().text_content()
最佳答案
from lxml import etree
root = etree.fromstring("...your xml...")
el, = root.xpath("//div[text() = 'the string']/preceding-sibling::*[9]")
关于python - 有没有办法在 Python 中为 lxml 指定固定(或可变)数量的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2367000/