Django / Pythonを使用してRESTful WebサービスからXMLを消費する方法は?
質問
PyXMLを使用する必要がありますか、それとも標準ライブラリに含まれるものですか?
解決
ElementTreeは、標準のPythonライブラリの一部として提供されます。 ElementTreeは純粋なPythonであり、cElementTreeはより高速なC実装です。
# Try to use the C implementation first, falling back to python
try:
from xml.etree import cElementTree as ElementTree
except ImportError, e:
from xml.etree import ElementTree
ここに使用例があります。ここでは、RESTful Webサービスからxmlを使用しています:
def find(*args, **kwargs):
"""Find a book in the collection specified"""
search_args = [('access_key', api_key),]
if not is_valid_collection(kwargs['collection']):
return None
kwargs.pop('collection')
for key in kwargs:
# Only the first keword is honored
if kwargs[key]:
search_args.append(('index1', key))
search_args.append(('value1', kwargs[key]))
break
url = urllib.basejoin(api_url, '%s.xml' % 'books')
data = urllib.urlencode(search_args)
req = urllib2.urlopen(url, data)
rdata = []
chunk = 'xx'
while chunk:
chunk = req.read()
if chunk:
rdata.append(chunk)
tree = ElementTree.fromstring(''.join(rdata))
results = []
for i, elem in enumerate(tree.getiterator('BookData')):
results.append(
{'isbn': elem.get('isbn'),
'isbn13': elem.get('isbn13'),
'title': elem.find('Title').text,
'author': elem.find('AuthorsText').text,
'publisher': elem.find('PublisherText').text,}
)
return results
他のヒント
可能な場合は常に標準ライブラリを使用することを好みます。 ElementTreeはpythonistaでよく知られているため、多くの例を見つけることができるはずです。その一部もCで最適化されているため、非常に高速です。
BeautifulSoup もあります。 Twitterのパブリックタイムラインからお気に入りになったすべてのツイートを抽出する方法の例を次に示します。
from BeautifulSoup import BeautifulStoneSoup
import urllib
url = urllib.urlopen('http://twitter.com/statuses/public_timeline.xml').read()
favorited = []
soup = BeautifulStoneSoup(url)
statuses = soup.findAll('status')
for status in statuses:
if status.find('favorited').contents != [u'false']:
favorited.append(status)
所属していません StackOverflow