[我正在尝试将在https://developers.google.com/youtube/v3/docs中作为示例找到的三个单独的代码放在一起:
在我的频道中创建播放列表(https://developers.google.com/youtube/v3/docs/playlists/insert)
搜索标题中带有给定关键字的视频(在我频道中的视频中[https://developers.google.com/youtube/v3/docs/search/list)
将视频添加到播放列表(https://developers.google.com/youtube/v3/docs/playlistItems/insert)
我能够成功地分别运行代码,但是无法将它们组合在一起。具体来说:创建播放列表后,代码需要获取播放列表ID。同样,当找到符合搜索条件的视频时,需要视频ID才能将其添加到播放列表中。我用过Python。请,有人可以帮忙吗?
这是我的代码:
import os
import google_auth_oauthlib.flow
import googleapiclient.discovery
import googleapiclient.errors
scopes = ["https://www.googleapis.com/auth/youtube.force-ssl"]
def main():
# Disable OAuthlib's HTTPS verification when running locally.
# *DO NOT* leave this option enabled in production.
os.environ["OAUTHLIB_INSECURE_TRANSPORT"] = "1"
api_service_name = "youtube"
api_version = "v3"
client_secrets_file = "client_secrets.json"
# 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",
forMine=True,
maxResults=50,
order="date",
q="searchcriteria",
type="video"
)
response = request.execute()
print(response)
vid=response['videoId']
request2 = youtube.playlistItems().insert(
part="snippet",
body={
"snippet": {
"playlistId": "myplaylistIdcomeshere",
"resourceId": {
"videoId": "vid",
"kind": "youtube#video",
"playlistId": "myplaylistIdcomeshereagain"
},
"position": 0
}
}
)
respons2 = request2.execute()
print(response2)
if __name__ == "__main__":
main()
根据搜索部分的响应,我得到以下内容(已编辑,删除了不必要的详细信息:]
{'kind':'youtube#searchListResponse','etag':'“ longetag”','nextPageToken':'anotherlongtext =','pageInfo':{'totalResults':1,'resultsPerPage':50}, 'items':[{'kind':'youtube#searchResult','etag':'“ theetagofthevideodfound”','id':{'kind':'youtube#video','videoId':'THISISWHATIWANT'}, 'snippet':{'publishedAt':'2020-02-22T19:33:03.000Z','channelId':'MyChannelTitle','title':'TitleOfTheVideo','description':``,'thumbnails':{ VideoThumbnails}},'channelTitle':'MyChannelTitle','liveBroadcastContent':'none'}}}]
我尝试过vid = response ['videoId']vid = response ['id']
但是他们都不起作用
向播放列表插入项目的响应应返回playlist resource,其中包含播放列表ID
https://developers.google.com/youtube/v3/docs/playlists#resource
类似地,当您搜索视频时,会得到一个search_resource
in response,其中包含ID为ID的视频列表
search_resource
只是想出一种可行的方法。将这段代码放在两次请求之间即可。如果有人遇到相同问题,请在此处发布:
https://developers.google.com/youtube/v3/docs/search#resource