如何使用python获取Youtube视频的持续时间?

Joa*_*iay 2 python youtube video youtube-api youtube-data-api

如何获得Youtube视频的持续时间?我正在尝试这个......

import gdata.youtube
import gdata.youtube.service

yt_service = gdata.youtube.service.YouTubeService()
entry = yt_service.GetYouTubeVideoEntry(video_id='the0KZLEacs')

print 'Video title: %s' % entry.media.title.text
print 'Video duration: %s' % entry.media.duration.seconds
Run Code Online (Sandbox Code Playgroud)

控制台响应

Traceback (most recent call last):
  File "/Users/LearningAnalytics/Dropbox/testing/youtube.py", line 8, in <module>
    entry = yt_service.GetYouTubeVideoEntry(video_id='the0KZLEacs')
  File "/Library/Python/2.7/site-packages/gdata/youtube/service.py", line 210, in GetYouTubeVideoEntry
    return self.Get(uri, converter=gdata.youtube.YouTubeVideoEntryFromString)
  File "/Library/Python/2.7/site-packages/gdata/service.py", line 1107, in Get
    'reason': server_response.reason, 'body': result_body}
gdata.service.RequestError: {'status': 410, 'body': 'No longer available', 'reason': 'Gone'}
Run Code Online (Sandbox Code Playgroud)

Joa*_*iay 7

获取YouTube视频时长的两种方法

第一种方式:


使用python和V3 youtube api这是每个视频的方式.您需要API密钥,您可以在此处获取:https://console.developers.google.com/

# -*- coding: utf-8 -*-
import json
import urllib

video_id="6_zn4WCeX0o"
api_key="Your API KEY replace it!"
searchUrl="https://www.googleapis.com/youtube/v3/videos?id="+video_id+"&key="+api_key+"&part=contentDetails"
response = urllib.urlopen(searchUrl).read()
data = json.loads(response)
all_data=data['items']
contentDetails=all_data[0]['contentDetails']
duration=contentDetails['duration']
print duration
Run Code Online (Sandbox Code Playgroud)

控制台响应:

>>>PT6M22S
Run Code Online (Sandbox Code Playgroud)

对应6分22秒.

第二种方式:


另一种但不适用于所有视频的方式是使用pafy外部包:

import pafy

url = "http://www.youtube.com/watch?v=cyMHZVT91Dw"
video = pafy.new(url)
print video.length
Run Code Online (Sandbox Code Playgroud)

我从https://pypi.python.org/pypi/pafy/0.3.42安装了pafy

  • 如果需要,您可以使用`duration = isodate.parse_duration(duration)`然后使用[isodate](https://pypi.python.org/pypi/isodate)解析ISO持续时间)包. (2认同)