使用 YouTube API 从用户提供的搜索词中获取 YouTube 视频 ID

时间:2021-06-17 23:25:27

标签: python youtube youtube-data-api

这里是一个非常新的初学者。我目前正在开发一个项目,用户可以在其中输入搜索词,并使用 YouTube 数据 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', 'vid​​eoId ':'YbJOTdZBX1g'},'片段':{'publishedAt':'2018-12-06T17:58:29Z','channelId':'UCBR8-60-B28hp2BmDPdntcQ','标题':'YouTube倒带 2018:人人控制倒带 | #YouTubeRewind', 'description': "YouTube Rewind 2018。庆祝定义 2018 年的视频、人物、音乐和时刻。#YouTubeRewind 没有创作者就不会回放:...", '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', 'width': 320, 'height': 180}, 'high': {'url': 'https://i.ytimg. com/vi/YbJOTdZBX1g/hqdefault.jpg', 'width': 480, 'height': 360}}, 'channelTitle': 'YouTube', 'liveBroadcastContent': 'none', 'publishTime': '2018-12- 06T17:58:29Z'}}]}

我想要做的是隔离“videoId”字符串,然后我将用它来组合一个 URL。 我觉得有一个非常简单的解决方案,我不认为这是一个初学者程序员。我能否获得一些帮助来隔离我需要继续我的项目的这部分?

在此先感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

因为 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)