Python解析XML提要错误:XPathEvalError:未定义的名称空间前缀 [英] Python Parse XML feed error: XPathEvalError: Undefined namespace prefix

查看:82
本文介绍了Python解析XML提要错误:XPathEvalError:未定义的名称空间前缀的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试处理XML文件,但出现此错误:

I'm trying to process an XML file, but I'm getting this error:

XPathEvalError: Undefined namespace prefix

在此行:

print "category =", item.xpath("./g:google_product_category")

这是XML文件:

<rss xmlns:g="http://base.google.com/ns/1.0" version="2.0">
<channel>
<title>example.net.br</title>
<link>http://www.example.net.br/</link>
<description>Data feed description.</description>
<item>
<title>
<![CDATA[
example
]]>
</title>
<link>
<![CDATA[
example
]]>
</link>
<description>
<![CDATA[
example]]>
</description>
<g:google_product_category>
<![CDATA[
example
]]>
</g:google_product_category>
...

这是我的代码:

headers = { 'User-Agent' : 'Mozilla/5.0' }
req = urllib2.Request(feed_url, None, headers)
file = urllib2.urlopen(req).read()

file = etree.fromstring(file)
for item in file.xpath('/rss/channel/item'):
    print "title =", item.xpath("./title/text()")[0]
    print "link =", item.xpath("./link/text()")[0]
    print "description =", item.xpath("./description/text()")[0]
    print "category =", item.xpath("./g:google_product_category")

我该如何解决?

推荐答案

xpath 方法接受一个额外的参数:namespaces

The xpath method accepts an additional parameter: namespaces

您是否可以尝试如下修改该行:

Could you try to modify the line as follows:

print "category =", item.xpath("./g:google_product_category", namespaces={'g': 'http://base.google.com/ns/1.0'})

可用信息来源此处

这篇关于Python解析XML提要错误:XPathEvalError:未定义的名称空间前缀的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆