有没有一种方法可以在Python中为lxml指定一个固定(或可变)数量的元素

问题描述:

必须有一种更简单的方法来实现这一点。我需要一些来自大量html文档的文本。在我的测试中,找到它的最可靠的方法是在div元素的text_content中查找特定的单词。如果我想检查具有我的文本的特定元素,我已经列举了我的div元素列表,并使用具有我的文本的索引,然后通过对索引进行操作来指定前一个元素。但我相信肯定有更好的办法。我似乎无法弄清楚。有没有一种方法可以在Python中为lxml指定一个固定(或可变)数量的元素

如果没有明确

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() 

lxml支持XPath

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

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

但是我是一个初学者,这对我有什么好处 - 我是使用html。我开始使用mytree = fromstring(the document),然后list_of_elements = mytree.cssselect('div') – PyNEwbie 2010-03-02 22:34:57

+0

@PyNEwbie:上面的xpath表达式只是一个例子,它应该像'elements [-1] .xpath(“之前的那样-sibling :: div [9]“)'在你的情况。 – jfs 2010-03-02 22:59:55

+0

我已经添加了组合的xpath表达式 – jfs 2010-03-02 23:23:34

使用类似simplehtmldom,然后提供一个指数?

这是否有诀窍?

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 
+0

我玩的祖先,现在试图找出如何操纵它的对象。我看到我有四个祖先。谢谢 – PyNEwbie 2010-03-02 22:36:34

+0

@PyNEwebie看到我编辑的答案。我最初给你的代码没有做你想做的事情。 – 2010-03-02 22:46:43

+0

谢谢我了解更多,这是有帮助的。 – PyNEwbie 2010-03-06 19:30:59