gpt4 book ai didi

python - 使用 Tenor 的 API

转载 作者:行者123 更新时间:2023-12-01 09:30:28 26 4
gpt4 key购买 nike

我的问题是我不知道如何处理 gif 搜索的结果。我使用了一个例子,我知道如何修改一些参数,但我不知道如何构建结果的gif。代码:

import requests
import json

# set the apikey and limit
apikey = "MYKEY" # test value
lmt = 8

# load the user's anonymous ID from cookies or some other disk storage
# anon_id = <from db/cookies>

# ELSE - first time user, grab and store their the anonymous ID
r = requests.get("https://api.tenor.com/v1/anonid?key=%s" % apikey)

if r.status_code == 200:
anon_id = json.loads(r.content)["anon_id"]
# store in db/cookies for re-use later
else:
anon_id = ""

# our test search
search_term = "love"

# get the top 8 GIFs for the search term
r = requests.get(
"https://api.tenor.com/v1/search?q=%s&key=%s&limit=%s&anon_id=%s" %
(search_term, apikey, lmt, anon_id))

if r.status_code == 200:
# load the GIFs using the urls for the smaller GIF sizes
top_8gifs = json.loads(r.content)
print (top_8gifs)
else:
top_8gifs = None

我想下载该文件。我知道我可以用 urllib 和 request 来做到这一点,但问题是我什至不知道什么是 top_8gifs。

希望有人能帮助我。我正在等待您的答复,感谢您的关注!!

最佳答案

首先你必须使用合法的 key 而不是MYKEY。完成此操作后,您将观察到此代码将打印您已发送的 GET 请求的输出。它是一个 json 文件,类似于 python 中的字典。现在您可以利用这个字典并获取网址。最好的策略是简单地打印出 json 的输出,并仔细观察字典的结构并从中提取 url。如果你想要更清楚,我们可以使用 python 中的 pprint 模块。它非常棒,将向您展示 json 文件的正确外观。这是代码的修改版本,它可以漂亮地打印 json 文件、打印 gif url 并下载 gif 文件。如果您愿意,您可以改进它并使用它。

import requests
import json
import urllib.request,urllib.parse,urllib.error
import pprint

# set the apikey and limit
apikey = "YOURKEY" # test value
lmt = 8

# load the user's anonymous ID from cookies or some other disk storage
# anon_id = <from db/cookies>

# ELSE - first time user, grab and store their the anonymous ID
r = requests.get("https://api.tenor.com/v1/anonid?key=%s" % apikey)

if r.status_code == 200:
anon_id = json.loads(r.content)["anon_id"]
# store in db/cookies for re-use later
else:
anon_id = ""

# our test search
search_term = "love"

# get the top 8 GIFs for the search term
r = requests.get(
"https://api.tenor.com/v1/search?q=%s&key=%s&limit=%s&anon_id=%s" %
(search_term, apikey, lmt, anon_id))

if r.status_code == 200:
# load the GIFs using the urls for the smaller GIF sizes
pp = pprint.PrettyPrinter(indent=4)
top_8gifs = json.loads(r.content)
pp.pprint(top_8gifs) #pretty prints the json file.
for i in range(len(top_8gifs['results'])):
url = top_8gifs['results'][i]['media'][0]['gif']['url'] #This is the url from json.
print (url)
urllib.request.urlretrieve(url, str(i)+'.gif') #Downloads the gif file.
else:
top_8gifs = None

关于python - 使用 Tenor 的 API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50010738/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com