使用Tenor的API

时间:2018-04-24 21:07:48

标签: python api urllib gif animated-gif

我的问题是我不知道如何处理搜索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和请求来做,但问题是我甚至不知道什么是top_8gifs。

我希望有人可以帮助我。我等你回答,谢谢你的关注!!

1 个答案:

答案 0 :(得分:0)

首先,您必须使用合法密钥而不是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