使用 Python 请求库引用 XML 结果
Referencing XML results using Python Requests Library
我正在 Python 中使用 Requests 库与公司的 API 合作。
但是结果是 XML 格式。
如何在 Python 或使用请求中引用我想要的数据?是否可以将此数据转换为 JSON?
这是一个例子:
XML:
<result xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/Starbucks.Location.WebAPI.Models">
<paging>
<total>21933</total>
<offset>0</offset>
<limit>10</limit>
<returned>10</returned>
</paging>
<stores>
<store>
<id>1</id>
<name>Store1</name>
<brandName>BrandName</brandName>
<storeNumber>34601-20281</storeNumber>
</store>
<store>
<id>2</id>
<name>Store2</name>
<brandName>BrandName</brandName>
<storeNumber>20281</storeNumber>
</store>
我的 Python 代码看起来有点像这样:
for i in range(0, 1):
myParameters = {'limit': '50', 'offset': i*50}
response = requests.get(url, params=myParameters)
print response #Here is where I want to print the data in json format
在该示例中响应 returns xml 格式。
我想创建一个 csv 或文本文件或使用每个商店的特定属性的东西。例如获取商店 ID 并将其放在 csv 文件的列中。
但我不知道如何在 xml 结果中引用 id 标签。我认为将数据转换为 json 会有所帮助,但是当我使用 Requests .json() 或 json 库时,我收到错误消息:No JSON object could be decoded
有许多 XML 解析器,但是 - 如果您有兴趣获得 JSON,您可能想尝试 xmltodict
和 json
,这可以让您到达那里在一行中。
json.dumps(xmltodict.parse(response))
我正在 Python 中使用 Requests 库与公司的 API 合作。
但是结果是 XML 格式。
如何在 Python 或使用请求中引用我想要的数据?是否可以将此数据转换为 JSON?
这是一个例子:
XML:
<result xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/Starbucks.Location.WebAPI.Models">
<paging>
<total>21933</total>
<offset>0</offset>
<limit>10</limit>
<returned>10</returned>
</paging>
<stores>
<store>
<id>1</id>
<name>Store1</name>
<brandName>BrandName</brandName>
<storeNumber>34601-20281</storeNumber>
</store>
<store>
<id>2</id>
<name>Store2</name>
<brandName>BrandName</brandName>
<storeNumber>20281</storeNumber>
</store>
我的 Python 代码看起来有点像这样:
for i in range(0, 1):
myParameters = {'limit': '50', 'offset': i*50}
response = requests.get(url, params=myParameters)
print response #Here is where I want to print the data in json format
在该示例中响应 returns xml 格式。
我想创建一个 csv 或文本文件或使用每个商店的特定属性的东西。例如获取商店 ID 并将其放在 csv 文件的列中。
但我不知道如何在 xml 结果中引用 id 标签。我认为将数据转换为 json 会有所帮助,但是当我使用 Requests .json() 或 json 库时,我收到错误消息:No JSON object could be decoded
有许多 XML 解析器,但是 - 如果您有兴趣获得 JSON,您可能想尝试 xmltodict
和 json
,这可以让您到达那里在一行中。
json.dumps(xmltodict.parse(response))