如何获取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
控制台响应
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'}
获取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
控制台响应:
>>>PT6M22S
对应6分22秒。
第二种方式:
另一种方法,但并非适用于所有视频是与pafy外部包:
import pafy
url = "http://www.youtube.com/watch?v=cyMHZVT91Dw"
video = pafy.new(url)
print video.length
我从安装了pafyhttps://pypi.python.org/pypi/pafy/0.3.42
有一个非常有用的库,叫做pytube,你可以从youtube中获得大量数据,比如频道名称、视频长度,你也可以下载视频或获取编解码器等https://pytube.io/en/latest/api.html
from pytube import YouTube
video = "youtube_url"
yt = YouTube(video) ## this creates a YOUTUBE OBJECT
video_length = yt.length ## this will return the length of the video in sec as an int
您也可以尝试以下
search_url = f'https://www.googleapis.com/youtube/v3/videos?id={video_id}&key={YT_KEY}&part=contentDetails'
req = urllib.request.Request(search_url)
response = urllib.request.urlopen(req).read().decode('utf-8')
data = json.loads(response)
all_data = data['items']
duration = all_data[0]['contentDetails']['duration']
minutes = int(duration[2:].split('M')[0])
seconds = int(duration[-3:-1])
这将使用utf-8编码对响应进行解码。这使我能够将它存储到json变量中。