ako*_*sch 12 python xpath lxml predicate
我想用lxml使用XPath表达式解析HTML.我的问题是匹配标签的内容:
比如给出了
<a href="http://something">Example</a>
Run Code Online (Sandbox Code Playgroud)
element我可以匹配href属性
.//a[@href='http://something']
Run Code Online (Sandbox Code Playgroud)
但给定的表达
.//a[.='Example']
Run Code Online (Sandbox Code Playgroud)
甚至
.//a[contains(.,'Example')]
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
预期产量为'a'.我得到'SyntaxError:无效的节点谓词'
sys*_*out 19
我会尝试:
.//a[text()='Example']
使用xpath()方法:
tree.xpath(".//a[text()='Example']")[0].tag
Run Code Online (Sandbox Code Playgroud)
如果你想使用iterfind(),findall(),find(),findtext(),请记住,ElementPath中没有值比较和函数等高级功能.
lxml.etree支持ElementTree和Element上的find,findall和findtext方法的简单路径语法,如原始ElementTree库(ElementPath)所知.作为lxml特定扩展,这些类还提供了一个xpath()方法,该方法支持完整XPath语法中的表达式,以及自定义扩展函数.