看看
import lxml.html, lxml.etree
url_cooking = 'http://cooking.stackexchange.com/feeds'
#lxml.etree version
data = lxml.etree.parse(url_cooking)
summary_nodes = data.xpath('.//feed/entry/summary')
print('Found ' + str(len(summary_nodes)) + ' summary nodes')
#lxml.html version
data = lxml.html.parse(url_cooking)
summary_nodes = data.xpath('.//feed/entry/summary')
print('Found ' + str(len(summary_nodes)) + ' summary nodes')
这两个版本当你发现,第二个版本不返回任何节点,但lxml.html
版本工作正常。 etree
版本不起作用,因为它期望名称空间,并且html
版本正在工作,因为它忽略了名称空间。部分下降http://lxml.de/lxmlhtml.html,它说:“HTML解析器明显忽略名称空间和一些其他XMLisms。”
注意当您打印etree版本的根节点(print(data.getroot())
)时,您会得到类似于<Element {http://www.w3.org/2005/Atom}feed at 0x22d1620>
的内容。这意味着它是一个名称空间为http://www.w3.org/2005/Atom
的提要元素。这是一个纠正版的etree代码。
import lxml.html, lxml.etree
url_cooking = 'http://cooking.stackexchange.com/feeds'
ns = 'http://www.w3.org/2005/Atom'
ns_map = {'ns': ns}
data = lxml.etree.parse(url_cooking)
summary_nodes = data.xpath('//ns:feed/ns:entry/ns:summary', namespaces=ns_map)
print('Found ' + str(len(summary_nodes)) + ' summary nodes')
'data.xpath( '// NS:进料/ NS:进入/ NS:摘要',命名空间= { '纳秒':“HTTP: //www.w3.org/2005/Atom'})' – reclosedev 2012-02-23 08:46:31
gah,难怪!看起来像api在某个时候重命名了'namespaces'关键字。用工作代码更新我的示例。 – gfortune 2012-02-23 09:05:55
非常感谢你的到来。在开始解析之前,我将开始检查根目录。 – MrCastro 2012-02-23 09:31:31