【发布时间】:2021-03-17 11:21:52
【问题描述】:
我正在做一个学校项目,我需要遍历 16 个类别(我已经将它们放在类列表中)以从 API 中获取所有笑话,但我似乎也做不到。
我知道我需要为每个类别迭代一次请求(在这种情况下,我已经知道它们是 16 并且我有一个名为“r”的变量存储它们。
我认为我需要使用 for 但似乎无法做到。除了获得 16 个类别的完整列表之外,我还需要将它们全部放入一个新的数据框中。
?? = 是要获取的类别名称 (0:"animal", 1:"career", 2:"celebrity", 3:"dev", 4:"explicit", 5:"fashion", 6:"food", 7:“历史”,8:“金钱”,9:“电影”,10:“音乐”,11:“政治”,12:“宗教”,13:“科学”,14:“运动”,15: “旅行”)
import requests
url = "https://matchilling-chuck-norris-jokes-v1.p.rapidapi.com/jokes/search"
querystring = {"query":"??"}
headers = {
'accept': "application/json",
'x-rapidapi-key': "xxxxx",
'x-rapidapi-host': "matchilling-chuck-norris-jokes-v1.p.rapidapi.com"
}
response = requests.request("GET", url, headers=headers, params=querystring)
print(response.text)
提前谢谢
----更多细节(编辑)
获取类别名称的 API:
import requests
url = "https://matchilling-chuck-norris-jokes-v1.p.rapidapi.com/jokes/categories"
headers = {
'accept': "application/json",
'x-rapidapi-key': "xxxx",
'x-rapidapi-host': "matchilling-chuck-norris-jokes-v1.p.rapidapi.com"
}
response = requests.request("GET", url, headers=headers)
a = response.text
a
输出: '["动物","职业","名人","开发","显式","时尚","食物","历史","金钱","电影","音乐","政治", “宗教”、“科学”、“运动”、“旅行”]'
然后我不是手动查询每个类别,而是试图找到一种方法来迭代所有类别并将所有输出放入 1 个数据帧中
import requests
url = "https://matchilling-chuck-norris-jokes-v1.p.rapidapi.com/jokes/search"
querystring = {"query":"animal"}
headers = {
'accept': "application/json",
'x-rapidapi-key': "xxxxxx",
'x-rapidapi-host': "matchilling-chuck-norris-jokes-v1.p.rapidapi.com"
}
response = requests.request("GET", url, headers=headers, params=querystring)
print(response.text)
希望我能够更好地解释我想要完成的事情。提前谢谢
【问题讨论】:
标签: json pandas api for-loop request