2017-10-30 4 views
1

私はatom_sample.xmlのタイトルとリンクを取得しようとしています。これは、他のRSSフィードのために働いていたのと同じコードを付けました。lxml解析原子 - 空の結果ですか?

from lxml import etree 
tree = etree.parse('atom_sample.xml') 
root = tree.getroot() 

titles = root.xpath('//entry/title/text()') 
links = root.xpath('//entry/link/@href') 
print(titles) 
print(links) 

結果: [] []これは完璧に働いていたIssues with python 3.x multiline regex?から他のRSSファイルを使用して

答えて

1

私はあなたの問題はlxml.etreeは、XML名前空間{http://www.w3.org/2005/Atom}を使用してXMLファイルを解析していることだと思う:私はイースリー、この名前空間を取り除く方法がわからないです

In [1]: from lxml import etree 
...: tree = etree.parse('atom_sample.xml') 
...: root = tree.getroot() 


In [2]: root 
Out[2]: <Element {http://www.w3.org/2005/Atom}feed at 0x7f198e8da808> 

が、あなたはthis質問への回答のいずれかを試みることができます。

とにかく私はxpathの各部分に<namespace>:<tag>を加えて、namespaces辞書をパラメータとして使ってxpathメソッドを使用します。例:

In [4]: namespaces = {'atom':'http://www.w3.org/2005/Atom'} 

In [5]: root.xpath('//atom:entry/atom:title/text()', namespaces=namespaces) 
Out[5]: 
['sample.00', 
'sample.01', 
'sample.02', 
'sample.03', 
'sample.04', 
'sample.05', 
'sample.06', 
'sample.07', 
'sample.08', 
'sample.09', 
'sample.10'] 

In [6]: root.xpath('//atom:entry/atom:link/@href', namespaces=namespaces) 
Out[6]: 
['https://myfeedurl.com/feed/00', 
    'https://myfeedurl.com/feed/01', 
    'https://myfeedurl.com/feed/02', 
    'https://myfeedurl.com/feed/03', 
    'https://myfeedurl.com/feed/04', 
    'https://myfeedurl.com/feed/05', 
    'https://myfeedurl.com/feed/06', 
    'https://myfeedurl.com/feed/07', 
    'https://myfeedurl.com/feed/08', 
    'https://myfeedurl.com/feed/09', 
    'https://myfeedurl.com/feed/10'] 
+0

ありがとうございます。この回避策は完璧に機能します! – Yves