2015-11-13 157 views
0

我如何獲得Youtube視頻的持續時間?我這個嘗試...如何使用python獲得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

你有沒有嘗試安裝pafy與其他一些視頻ID? – utkbansal

+0

410錯誤意味着在YouTube的結尾有什麼不好的,不是你的 – utkbansal

+0

是的,我嘗試了differents ID而不是作品 –

回答

3

兩種方式來獲得一個YouTube視頻時長

第一種方式:


用python和V3 y這是每個視頻的方式。您需要的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 

我從https://pypi.python.org/pypi/pafy/0.3.42

+0

如果需要,可以使用解析' 持續時間= isodate.parse_duration(持續時間)',然後將ISO持續時間'video_dur = duration.total_seconds()'與[isodate](https://pypi.python.org/pypi/isodate)包。 –

相關問題