用youtube api获取我的视频时长

时间:2017-03-12 15:29:40

标签: python youtube-api

我正在使用此youtube api示例,以获取上传视频的持续时间。在此资源表示https://developers.google.com/youtube/v3/docs/videos#snippet中,我可以看到json的结构,但无法获得此部分

enter image description here

目前,我设法通过“视频发布”来获取contentDetails'它看起来像({u'videoPublishedAt': u'2013-03-13T00:05:41.000Z', u'videoId': u'6PKHl3Kvppk'})

我添加了' contentDetails'到'部分'

  playlistitems_list_request = youtube.playlistItems().list(
    playlistId=uploads_list_id,
    part="snippet,contentDetails",
    maxResults=50
  )

然后在上一部分video_id = playlist_item["contentDetails"]

中更改了while playlistitems_list_request:

video_id = playlist_item["contentDetails"]["duration"]提供 KeyError:'期限'

这是没有身份验证部分和导入的完整代码。完整版可以在https://github.com/youtube/api-samples/blob/master/python/my_uploads.py

找到
# Retrieve the contentDetails part of the channel resource for the
# authenticated user's channel.
channels_response = youtube.channels().list(
  mine=True,
  part="contentDetails"
).execute()

for channel in channels_response["items"]:
  # From the API response, extract the playlist ID that identifies the list
  # of videos uploaded to the authenticated user's channel.
  uploads_list_id = channel["contentDetails"]["relatedPlaylists"]["uploads"]

  print "Videos in list %s" % uploads_list_id

  # Retrieve the list of videos uploaded to the authenticated user's channel.
  playlistitems_list_request = youtube.playlistItems().list(
    playlistId=uploads_list_id,
    part="snippet,contentDetails",
    maxResults=50
  )

  while playlistitems_list_request:
    playlistitems_list_response = playlistitems_list_request.execute()

    # Print information about each video.
    for playlist_item in playlistitems_list_response["items"]:
      title = playlist_item["snippet"]["title"]
      video_id = playlist_item["contentDetails"]
      print "%s (%s)" % (title, video_id)

    playlistitems_list_request = youtube.playlistItems().list_next(
      playlistitems_list_request, playlistitems_list_response)

  print

1 个答案:

答案 0 :(得分:2)

这里是如何获得持续时间的。我只是使用Youtube API Explorer Videos.list给你试试看,然后在你的代码上实现它。

我提供了id的参数,它是youtube vid的videoId和partDetails的部分。

成功的回复会将视频的持续时间与其他元数据一起返回:

  "contentDetails": {
    "duration": "PT1M28S",
    "dimension": "2d",
    "definition": "hd",
    "caption": "false",
    "licensedContent": false,
    "projection": "rectangular",
    "hasCustomThumbnail": false
   }

这里,1分28秒。   请查看Youtube Videos.list以获取更多参考信息。