【问题标题】:Getting YouTube Video ID from user-supplied search term using YouTube API使用 YouTube API 从用户提供的搜索词中获取 YouTube 视频 ID
【发布时间】:2021-09-02 17:53:08
【问题描述】:

这里是新手。我目前正在开发一个用户可以输入搜索词并使用 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', 'vid​​eoId ':'YbJOTdZBX1g'},'sn-p':{'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','width':480,'height':360}},'channelTitle':'YouTube','liveBroadcastContent':'none','publishTime':'2018-12- 06T17:58:29Z'}}]}

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

提前感谢您的所有帮助。

【问题讨论】:

  • 你能添加 print(type(response)) 并告诉我它输出什么
  • 我已经把它放在底部,第 53 行。打印(响应)。
  • 不,我想要响应的类型而不是响应的内容。换句话说,print(type(response)) 的输出而不仅仅是print(response)
  • 除了正常的输出外,最后我还看到了 dict>。很抱歉造成混乱。

标签: python youtube youtube-data-api


【解决方案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)

【讨论】:

  • 这是有效的。非常感谢您的帮助!
猜你喜欢
  • 2019-12-14
  • 2016-01-21
  • 2011-09-27
  • 1970-01-01
  • 2019-08-23
  • 1970-01-01
  • 2014-07-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多