Моя проблема в том, что я не умею работать с результатом поиска гифки. Я использовал пример, я знаю, как изменить некоторые параметры, но я не знаю, как построить гифки результата. Код:
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.
Я надеюсь, что кто-нибудь может мне помочь. Жду ответа, спасибо за внимание !!






Прежде всего, вы должны использовать законный ключ вместо MYKEY. Как только вы это сделаете, вы увидите, что этот код распечатает результат отправленного вами GET-запроса. Это файл json, который похож на словарь в Python. Итак, теперь вы можете использовать этот словарь и получить URL-адреса. Лучшая стратегия - просто распечатать вывод json, внимательно изучить структуру словаря и извлечь из него URL-адрес. Если вы хотите большей ясности, мы можем использовать модуль pprint в python. Это довольно круто и покажет вам, как правильно выглядит файл json. Вот модифицированная версия вашего кода, которая красиво печатает файл json, печатает URL-адреса gif и загружает файлы 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