将 URL 中的 XML 解析为 python 对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24124643/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 04:03:23  来源:igfitidea点击:

Parse XML from URL into python object

pythonxmldjangoxml-parsingurllib2

提问by smilebomb

The goodreads website has this API for accessing a user's 'shelves:' https://www.goodreads.com/review/list/20990068.xml?key=nGvCqaQ6tn9w4HNpW8kquw&v=2&shelf=toread

goodreads 网站具有用于访问用户“货架”的 API:https: //www.goodreads.com/review/list/20990068.xml?key=nGvCqaQ6tn9w4HNpW8kquw &v=2&shelf=toread

It returns XML. I'm trying to create a django project that shows books on a shelf from this API. I'm looking to find out how (or if there is a better way than) to write my view so I can pass an object to my template. Currently, this is what I'm doing:

它返回 XML。我正在尝试创建一个 django 项目,该项目通过此 API 在书架上显示书籍。我正在寻找如何(或者是否有更好的方法)来编写我的视图,以便我可以将对象传递给我的模板。目前,这就是我正在做的事情:

import urllib2

def homepage(request):
    file = urllib2.urlopen('https://www.goodreads.com/review/list/20990068.xml?key=nGvCqaQ6tn9w4HNpW8kquw&v=2&shelf=toread')
    data = file.read()
    file.close()
    dom = parseString(data)

I'm not entirely sure how to manipulate this object if I'm doing this correctly. I'm following this tutorial.

如果我正确地执行此操作,我不完全确定如何操作此对象。我正在关注本教程

采纳答案by alecxe

I'd use xmltodictto make a python dictionary out of the XMLdata structure and pass this dictionary to the template inside the context:

我会使用数据结构xmltodict制作一个 python 字典XML,并将这个字典传递给上下文中的模板:

import urllib2
import xmltodict

def homepage(request):
    file = urllib2.urlopen('https://www.goodreads.com/review/list/20990068.xml?key=nGvCqaQ6tn9w4HNpW8kquw&v=2&shelf=toread')
    data = file.read()
    file.close()

    data = xmltodict.parse(data)
    return render_to_response('my_template.html', {'data': data})

回答by gies0r

xmltodictusing urllib3

xmltodict使用 urllib3

import traceback
import urllib3
import xmltodict

def getxml()
    url = "https://yoursite/your.xml"
    import urllib3
    import xmltodict


    http = urllib3.PoolManager()

    response = http.request('GET', url)
    try:
        data = xmltodict.parse(response.data)
    except:
        print("Failed to parse xml from response (%s)" % traceback.format_exc())
    return data

回答by Vincent

xmltodictusing requests

xmltodict使用 requests

import requests
import xmltodict

url = "https://yoursite/your.xml"
response = requests.get(url)
data = xmltodict.parse(response.content)