首页 > 解决方案 > 使用 YouTube API 从用户提供的搜索词中获取 YouTube 视频 ID

问题描述

这里非常新的初学者。我目前正在开发一个用户可以输入搜索词并使用 YouTube Data API v3 获取视频 ID 的项目。然后,此视频 ID 用于组装一个 URL,然后我使用该 URL 将视频下载到我的计算机上。这就是我用来做这件事的。(忽略我已经导入的库,稍后我会清理这些库)

from __future__ import print_function
import pathlib
from pathlib import Path
import pytube
import os
import os.path
import googleapiclient
import google_auth_httplib2
import google_auth_oauthlib
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from pytube import YouTube



import os

import google_auth_oauthlib.flow
import googleapiclient.discovery
import googleapiclient.errors

scopes = ["https://www.googleapis.com/auth/youtube.force-ssl"]
userVideoChoice=input("Please enter the title of the song you want to use. ")
def main():
    
    os.environ["OAUTHLIB_INSECURE_TRANSPORT"] = "1"

    api_service_name = "youtube"
    api_version = "v3"
    client_secrets_file = ("CLIENT SECRET FILE HERE")

    # Get credentials and create an API client
    flow = google_auth_oauthlib.flow.InstalledAppFlow.from_client_secrets_file(
        client_secrets_file, scopes)
    credentials = flow.run_console()
    youtube = googleapiclient.discovery.build(
        api_service_name, api_version, credentials=credentials)

    request = youtube.search().list(
        part="snippet",
        maxResults=1,
        q=userVideoChoice
    )
    response = request.execute()

    print(response)

if __name__ == "__main__":
    main()

因此,对于“Youtube Rewind 2018”的搜索查询,Youtube API 将返回:

{'kind':'youtube#searchListResponse','etag':'HEbvpHREbTpRzcvryx2ubH2tnDo','nextPageToken':'CAEQAA','regionCode':'US','pageInfo':{'totalResults':1000000,'resultsPerPage': 1},'items':[{'kind':'youtube#searchResult','etag':'VX4FEWIWXekE8cUP4SCMNhGl7Ek','id':{'kind':'youtube#video','videoId':'YbJOTdZBX1g'}, 'snippet': {'publishedAt': '2018-12-06T17:58:29Z', 'channelId': 'UCBR8-60-B28hp2BmDPdntcQ', 'title': 'YouTube 倒带 2018:每个人都控制倒带 | #YouTubeRewind', 'description': "YouTube Rewind 2018。庆祝定义 2018 年的视频、人物、音乐和时刻。#YouTubeRewind 没有创作者就不会是 Rewind: ...", 'thumbnails': {'default ':{'url':'https://i.ytimg.com/vi/YbJOTdZBX1g/default.jpg','width':120,'height':90},'medium':{'url':' https://i.ytimg.com/vi/YbJOTdZBX1g/mqdefault.jpg','宽度':320,'高度':180},'高':{'url':'https://i.ytimg. com/vi/YbJOTdZBX1g/hqdefault.jpg','宽度':480,'高度':360}},

我要做的是隔离“videoId”字符串,然后我将用它来组装一个 URL。我觉得那里有一个非常简单的解决方案,而我作为初学者程序员并没有看到。我可以得到一些帮助来隔离我需要继续我的项目的这部分吗?

预先感谢您的所有帮助。

标签: pythonyoutubeyoutube-data-api

解决方案


由于response是字典,因此您可以通过索引访问它的元素。response[items]是一个列表,因此最好遍历该列表中的所有项目。有了这个,我们可以生成一个 video_ids 列表,如下所示:

video_ids = []
for item in response['items']:
    video_ids.append(item['id']['videoId'])

print(video_ids)

此代码位于 request.execute() 下

作为旁注,使用 PrettyPrinter 更容易理解字典。我会添加类似的东西

import pprint
pp = pprint.PrettyPrinter(indent=2).pprint

在您的导入结束时使用pp(response)而不是print(response).


推荐阅读