use*_*174 2 python django rest json
所以我的目标是使用 ISO Alpha-2 国家/地区代码找到一个国家/地区的名称。我认为这是第一次尝试 RESTful API(确切地说是世界银行 API )的好时机。我开始使用本教程来尝试实现我的目标,它似乎requests.get()是我问题的答案,我尝试了一下并得到了这个:
(InteractiveConsole)
>>> import requests
>>> resp = requests.get('http://api.worldbank.org/countries/br')
>>> resp
<Response [200]>
>>> resp.json()
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "C:\Users\username\AppData\Local\Programs\Python\Python35\lib\site-packages\requests\models.py", line 866, in json
return complexjson.loads(self.text, **kwargs)
File "C:\Users\username\AppData\Local\Programs\Python\Python35\lib\json\__init__.py", line 315, in loads
s, 0)
json.decoder.JSONDecodeError: Unexpected UTF-8 BOM (decode using utf-8-sig): line 1 column 1 (char 0)
Run Code Online (Sandbox Code Playgroud)
我不太确定出了什么问题或者它告诉我要做什么(我对 JSON 不太熟悉)。对此有什么解释以及如何解决它吗?
我在用:
Windows 7 64 位
Python 3.5.1
姜戈 1.10
requests包 2.13.0
您从该端点获得的响应不是 JSON。因此,即使使用json.loads().
它返回一个必须以不同方式解析的 XML。
你可以使用:
import requests
import xml.etree.ElementTree
resp = requests.get('http://api.worldbank.org/countries/br')
root = xml.etree.ElementTree.fromstring(resp.content)
print( root.find("{http://www.worldbank.org}country")[1].text )
Run Code Online (Sandbox Code Playgroud)
要了解如何正确解析 XML 数据,您应该阅读文档。
| 归档时间: |
|
| 查看次数: |
7389 次 |
| 最近记录: |