lxml - 难度解析stackexchange rss feed
Hialxml - 难度解析stackexchange rss feed
我在解析python中的stackexchange的rss订阅源时出现问题。 当我试图让摘要节点,一个空列表返回
我一直在试图解决这个问题,但不能左右我的头。
任何人都可以帮忙吗? 感谢 一个
In [3o]: import lxml.etree, urllib2
In [31]: url_cooking = 'http://cooking.stackexchange.com/feeds'
In [32]: cooking_content = urllib2.urlopen(url_cooking)
In [33]: cooking_parsed = lxml.etree.parse(cooking_content)
In [34]: cooking_texts = cooking_parsed.xpath('.//feed/entry/summary')
In [35]: cooking_texts
Out[35]: []
看看
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')
问题是命名空间。
运行以下命令:
cooking_parsed.getroot().tag
,你会看到,如果你导航到饲料条目之一的元素的命名空间
{http://www.w3.org/2005/Atom}feed
同样。
这意味着在LXML右XPath是:
print cooking_parsed.xpath(
"//a:feed/a:entry",
namespaces={ 'a':'http://www.w3.org/2005/Atom' })
不知何故,我怀疑这个答案对你来说比对我更容易。 ;)Sheepishly碰到你的答案,并随时指出我在我的任何错误。 – gfortune 2012-02-23 09:14:37
'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