Python调用TheDogAPI的Get请求返回列表,无法提取url值的问题
解决TheDogAPI返回列表无法提取URL的问题
调用无需认证的公开API https://api.thedogapi.com/v1/images/search 发送GET请求时,返回的随机结果是包含单个字典的列表,直接通过键名提取url会触发类型错误。
测试代码
import requests r = requests.get("https://api.thedogapi.com/v1/images/search?format=json") print(r.json())
返回结果
[{'id': 'QBvGwfKLW', 'url': 'https://cdn2.thedogapi.com/images/QBvGwfKLW.jpg', 'width': 2322, 'height': 4128}]
错误代码
import requests r = requests.get("https://api.thedogapi.com/v1/images/search?format=json") # 尝试直接通过键名提取url link = r.json()["url"] print(link)
报错信息
TypeError: list indices must be integers or slices, not str
解决方案
接口返回的是列表,列表只能用整数索引或切片访问,不能直接用字符串键名。需要先获取列表中的第一个元素(索引0),再从该字典中提取url:
修正后的代码
import requests r = requests.get("https://api.thedogapi.com/v1/images/search?format=json") # 先取列表第一个元素,再提取url dog_data = r.json()[0] link = dog_data["url"] print(link)
也可以简写为一行:
link = r.json()[0]["url"]
额外提示
如果通过limit参数指定返回多条数据,可通过循环遍历列表获取所有图片URL:
import requests r = requests.get("https://api.thedogapi.com/v1/images/search?format=json&limit=3") for dog in r.json(): print(dog["url"])
内容的提问来源于stack exchange,提问作者Kevin Provoost
相关产品推荐
相关产品推荐

