You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

从API获取URL时遇TypeError: string indices must be integers错误求助

解决TypeError: string indices must be integers错误

问题场景

你尝试从API获取URL时遇到错误:

TypeError: string indices must be integers

API返回的数组数据格式如下(JSON结构):

[{"created_utc": 1643524062,"title": "title","url": "https://i.redd.it/tmd5shz9rre81.gif",},{"created_utc": 1643530657,"title": "title","url": "https://i.redd.it/qqjykysxase81.gif",}]

你的代码:

url = "https://reddit-meme.p.rapidapi.com/memes/trending"

headers = {
    "X-RapidAPI-Key": "83df5aba87msh4580fa40781b33cp12157bjsnb4b412cb57da",
    "X-RapidAPI-Host": "reddit-meme.p.rapidapi.com"
}

response = requests.request("GET", url, headers=headers)

print(response.text[0]["url"])

错误原因

response.text返回的是字符串类型的JSON数据,你直接用[0]["url"]去访问,相当于试图给字符串用字典的键来索引,而字符串的索引只能是整数(比如response.text[0]取的是字符串的第一个字符[),所以触发TypeError。

修正方案

需要先把字符串格式的响应内容解析为Python的列表/字典对象,使用response.json()方法即可:

url = "https://reddit-meme.p.rapidapi.com/memes/trending"

headers = {
    "X-RapidAPI-Key": "83df5aba87msh4580fa40781b33cp12157bjsnb4b412cb57da",
    "X-RapidAPI-Host": "reddit-meme.p.rapidapi.com"
}

response = requests.request("GET", url, headers=headers)
# 解析JSON响应为Python列表
data = response.json()
# 访问第一个元素的url字段
print(data[0]["url"])

如果要遍历所有返回的URL,可以这样写:

for item in data:
    print(item["url"])

内容的提问来源于stack exchange,提问作者Serget

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 22:54:36