Работа с API Тенора - PullRequest
0 голосов
/ 25 апреля 2018

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

Надеюсь, кто-нибудь сможет мне помочь.Я жду вашего ответа, спасибо за внимание !!

1 Ответ

0 голосов
/ 25 апреля 2018

Прежде всего, вы должны использовать законный ключ вместо 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
...