有没有办法在Python中为lxml指定固定(或可变)数量的元素

2024-09-28 05:25:03 发布

您现在位置:Python中文网/ 问答频道 /正文

一定有更简单的方法。我需要一些文本从大量的html文档。在我的测试中,最可靠的方法是在div元素的文本内容中查找特定的单词。如果我想检查包含我的文本的元素上面的特定元素,我已经列举了我的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()

Tags: ofthe方法textin文本div元素
3条回答

使用类似simplehtmldom的内容,然后提供索引?你知道吗

这样行吗?你知道吗

from itertools import islice
ancestor = islice(theitem.iterancestors(), 4) # To get the fourth ancestor

编辑我是个白痴,那没用。您需要将其包装到一个helper函数中,如下所示:

def nthparent(element, n):
    parent = islice(element.iterancestors(), n, n+1)
    return parent[0] if parent else None

ancestor = nthparent(theitem, 4) # to get the 4th parent

lxml支持XPath

from lxml import etree
root = etree.fromstring("...your xml...")

el, = root.xpath("//div[text() = 'the string']/preceding-sibling::*[9]")

相关问题 更多 >

    热门问题