2015-02-08 20 views
0

我有一个我正在尝试解析的html页面。这是我在用lxml做的事情:lxml解析中的命名空间参数

node=etree.fromstring(html) 
>>> node 
<Element {http://www.w3.org/1999/xhtml}html at 0x110676a70> 
>>> node.xpath('//body') 
[] 
>>> node.xpath('body') 
[] 

不幸的是,我所有的xpath调用现在都返回一个空列表。为什么会发生这种情况,我如何解决这个问题?

+0

它可能是所有的标签命名空间,因为你已经猜到了,可能是最简单的使用HTML解析模块http://lxml.de/lxmlhtml.html#parsing-html – Anentropic 2015-02-08 20:57:49

+1

否则与命名空间,你会有可以这样做:'node.xpath('// html:body',namespaces = {'html':'http://www.w3.org/1999/xhtml'})' – Anentropic 2015-02-08 20:58:39

回答

1

您需要使用命名空间前缀同时查询。像

node.xpath('//html:body', namespaces={'html': 'http://...'}) 

,或者您可以使用.nsmap

node.xpath('//html:body', namespaces=node.nsmap) 

这是假设所有的命名空间由node指出标记定义。这通常适用于大多数xml文档。

1

你可以在这里添加命名空间,如下所示:

>>> node.xpath('//xmlns:tr', namespaces={'xmlns':'http://www.w3.org/1999/xhtml'}) 
[<Element {http://www.w3.org/1999/xhtml}tr at 0x11067b6c8>, <Element {http://www.w3.org/1999/xhtml}tr at 0x11067b710>] 

和更好的方式来做到这将是使用lxml's HTML解析器:

>>> node=lxml.html.fromstring(html) 
>>> node.findall('body') 
[<Element body at 0x1106b8f18>] 
+0

lxml.html.fromstring – syzygy 2016-06-27 06:16:52