2017-05-25 19 views
0

私は、XMLファイルを処理しようとしているが、私はこのエラーを取得しています:この行のPythonの解析XMLフィードエラー:XPathEvalError:未定義の名前空間接頭辞

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") 

どうすればこの問題を解決できますか?

答えて

2

のxpathメソッドは追加パラメータを受け入れる:here

入手可能な情報の

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

ソースを次のように名前空間が

次の行を変更しようとすることができ

関連する問題