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

时间:2010-03-02 21:40:14

标签: python html lxml screen-scraping

必须有一种更简单的方法来做到这一点。我需要一些来自大量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()

3 个答案:

答案 0 :(得分:3)

lxml支持XPath

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

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

答案 1 :(得分:1)

这可以解决这个问题吗?

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

编辑我是个白痴,不能做到这一点。您需要将其包装在辅助函数中,如下所示:

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

答案 2 :(得分:0)

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