2010-04-14 32 views
11

我想用lxml使用XPath表达式解析HTML。我的问题是匹配对一个标签的内容:如何匹配XPath中的元素内容(lxml)?

例如给定的使用

.//a[@href='http://something'] 

<a href="http://something">Example</a> 

元件我可以匹配href属性,但给出的表达式

.//a[.='Example'] 

或甚至

.//a[contains(.,'Example')] 

lxml抛出'invalid node predicate'异常。

我在做什么错?

编辑:

示例代码:

from lxml import etree 
from cStringIO import StringIO 

html = '<a href="http://something">Example</a>' 
parser = etree.HTMLParser() 
tree = etree.parse(StringIO(html), parser) 

print tree.find(".//a[text()='Example']").tag 

预期输出为 'a'。我得到 '语法错误:无效的节点谓词'

+2

而不是使用StringIO的,你也可以使用etree.fromstring()来解析您的HTML。 – 2011-08-04 07:09:54

回答

18

我会尝试使用:使用XPath

.//a[text()='Example']

()方法:

tree.xpath(".//a[text()='Example']")[0].tag 

如果您想情况下使用iterfind() ,findall(),find(),findtext(),请记住,值比较和函数等高级功能在ElementPath中不可用。

lxml.etree supports the simple path syntax of the find, findall and findtext methods on ElementTree and Element, as known from the original ElementTree library (ElementPath). As an lxml specific extension, these classes also provide an xpath() method that supports expressions in the complete XPath syntax, as well as custom extension functions.

+0

我不想根据href找到链接,但基于它包含的文本:上例中的“示例”:) .//a[@href='http://something']工程它的方式... – akosch 2010-04-14 13:59:27

+1

你需要删除= .//a[text()='示例'] – Greg 2010-04-14 14:20:06

+0

感谢您的建议,但是这个提出了“SyntaxError:invalid node predicate” – akosch 2010-04-14 14:20:25

相关问题