YouTube API V3 搜索 Python

0 投票
1 回答
3080 浏览
提问于 2025-04-18 01:02

我正在尝试使用YouTube API V3的搜索功能。我有一个Flask的网页应用,想把搜索结果显示成网页上的几行。

我最开始参考了谷歌开发者页面(在终端上运行得很好),然后找到了这个听起来很不错的例子,它可以从结果中输出缩略图和超链接。不过这个例子是运行在谷歌的应用引擎上,而我想做的是创建一个Flask应用。

所以,凭着我有限的知识,我尝试把这两个结合起来,适应我的需求。

#!/usr/bin/python

from apiclient.discovery import build
from apiclient.errors import HttpError
from oauth2client.tools import argparser
import sys
import os
import urllib

# Set API_KEY to the "API key" value from the "Access" tab of the
# Google APIs Console http://code.google.com/apis/console#access
# Please ensure that you have enabled the YouTube Data API and Freebase API
# for your project.
API_KEY = "REPLACE ME" #Yes I did replace this with my API KEY
YOUTUBE_API_SERVICE_NAME = "youtube"
YOUTUBE_API_VERSION = "v3"
QUERY_TERM = "dog"

def search_by_keyword():
    youtube = build(
      YOUTUBE_API_SERVICE_NAME, 
      YOUTUBE_API_VERSION, 
      developerKey=API_KEY
    )
    search_response = youtube.search().list(
      q=QUERY_TERM,
      part="id,snippet",
      maxResults=25
    ).execute()

    videos = []

    for search_result in search_response.get("items", []):
    if search_result["id"]["kind"] == "youtube#video":
            videos.append("%s (%s)" % (search_result["snippet"]["title"],
                                       search_result["id"]["videoId"]))

print "Videos:\n", "\n".join(videos), "\n"

if __name__ == "__main__":
  try:
    youtube_search()
  except HttpError, e:
    print "An HTTP error %d occurred:\n%s" % (e.resp.status, e.content)

我其实想要的是把结果返回到我的网页上,而不是仅仅在终端打印出来,但我觉得一步一步来比较好。如果我能在终端上让它工作,那么我就可以在网页上整理这些结果,但这并没有我想象的那么简单。

目前我遇到了一个错误;

Traceback (most recent call last):
  File "search.py", line 38, in <module>
    print "Videos:\n", "\n".join(videos), "\n"
NameError: name 'videos' is not defined

这是我面临的第一个主要障碍,因为我原本期待它能像我从中获取的两个例子那样工作。

我的第二个问题是,如果我能解决上面的错误,怎么把结果转换成网页上的表格呢?

我计划有

@app.route('/search')

把上面的代码包含进来,然后;

return render_template ('search.html')

但我不确定怎么把结果传回去,我还需要用print吗,还是应该用其他的术语?我想用每个返回的VideoID来整理缩略图和链接。

1 个回答

1

你的视频列表是一个局部变量,只在你的“search_by_keyword()”这个函数内部存在,外面是无法访问到这个视频变量的。如果想要使用这个变量,你可以像这样返回它:

def search_by_keyword():
youtube = build(
  YOUTUBE_API_SERVICE_NAME, 
  YOUTUBE_API_VERSION, 
  developerKey=API_KEY
)
search_response = youtube.search().list(
  q=QUERY_TERM,
  part="id,snippet",
  maxResults=25
).execute()

videos = []

for search_result in search_response.get("items", []):
if search_result["id"]["kind"] == "youtube#video":
        videos.append("%s (%s)" % (search_result["snippet"]["title"],
                                   search_result["id"]["videoId"]))
return videos

在你的主函数中,你可以使用类似下面的代码:

videos = search_by_keyword()

这样的话,你就可以把视频打印到控制台上,或者用Flask把它发送到一个模板中。

撰写回答