如何在Django/Python中消费RESTful web服务的XML?
我应该使用PyXML还是标准库里的东西?
3 个回答
0
还有一个叫做 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)
3
我总是尽量使用标准库,因为这样更可靠。ElementTree在Python爱好者中非常有名,所以你应该能找到很多例子来学习。它的一些部分还用C语言进行了优化,所以运行速度很快。
10
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 网络服务获取 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