以下是 get 请求的输出:
"ip": "8.8.8.8",
"city": "Mountain View",
"region": "California",
"country": "US",
"loc": "37.3860,-122.0838",
"postal": "94035",
"timezone": "America/Los_Angeles"
如何将它们分解为不同的变量?
例如,我需要从"ip"获取 8.8.8.8:"8.8.8.8"并需要打印
有没有简单的方法可以做到这一点?我正在做一种更难的方式,在某些情况下是不可能的
假设输出在一个名为 response 的变量中,并且是 json 或字典的形式,然后
ip = response.pop('ip')
city = response.pop('city')
等等
如果响应不是字典格式,则使用 get 操作
ip = response.get('ip')
city = response.get('city')
以下是使用请求获取数据并将响应读取到变量中的代码:
response = request.get(url)
if response: #<-- If response is in 200-299 range: True
resp_data=response.json() #<-- Convert output JSON stream into python readable object dict
ip = resp_data.get('ip') #<-- .get function to avoid key error
city = resp_data.get('city')
region = resp_data.get("region")
else:
print(f"Error Occurred with Status Code {response.status_code}")
print(f"Error : {response.text}")
- 确保检查每个request.get操作的状态代码,当请求失败时,将不会返回数据。
- 即使响应成功,也需要使用
response.json()
将 json 输出转换为 python 可读字典。 - 使用
dict.get("<dict_key>")
函数将变量提取为无效键错误。