我对下面的测试文档测试:为什么xpath在使用lxml处理XHTML文档时不工作(在python中)?
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>hi there</title>
</head>
<body>
<img class="foo" src="bar.png"/>
</body>
</html>
如果我解析使用lxml.html文件,我可以用XPath就好得到IMG:,
>>> root = lxml.html.fromstring(doc)
>>> root.xpath("//img")
[<Element img at 1879e30>]
但是如果我解析文档的XML,并得到IMG标记,我得到一个空的结果:
>>> tree = etree.parse(StringIO(doc))
>>> tree.getroot().xpath("//img")
[]
我可以浏览到直接的元素:
>>> tree.getroot().getchildren()[1].getchildren()[0]
<Element {http://www.w3.org/1999/xhtml}img at f56810>
但当然这并不能帮助我处理任意文件。我也希望能够查询etree得到的XPath表达式将直接确定此元素,从技术上讲我可以这样做:
>>> tree.getpath(tree.getroot().getchildren()[1].getchildren()[0])
'/*/*[2]/*'
>>> tree.getroot().xpath('/*/*[2]/*')
[<Element {http://www.w3.org/1999/xhtml}img at fa1750>]
但是,XPath是,再次,显然不是有益的解析任意文件。
显然我错过了这里的一些关键问题,但我不知道它是什么。我最好的猜测是它与命名空间有关,但唯一定义的命名空间是默认的,我不知道我还需要考虑命名空间。
那么,我错过了什么?
从报价http://codespeak.net/lxml/xpathxslt.html <<或者,你可以提供一个命名空间关键字参数,这应该是映射字典命名空间URI中使用的名称空间前缀>> – 2009-06-14 14:50:07