gpt4 book ai didi

Python 解析 XML 提要错误 : XPathEvalError: Undefined namespace prefix

转载 作者:行者123 更新时间:2023-12-04 03:06:12 25 4
gpt4 key购买 nike

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

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 方法接受一个额外的参数:命名空间

您能否尝试如下修改该行:

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

可用信息来源 here

关于Python 解析 XML 提要错误 : XPathEvalError: Undefined namespace prefix,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44188237/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com