如何获取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'}
答案 0 :(得分:7)
第一种方式:
使用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
安装了pafy
答案 1 :(得分:1)
您也可以尝试以下
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变量中。