Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the duration of Youtube video with python?

How can I get the duration of Youtube video? I am trying with this...

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

Console response

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'}
like image 748
Joan Triay Avatar asked Dec 19 '22 22:12

Joan Triay


1 Answers

Two ways to get a youtube video duration

First way:


With python and V3 youtube api this is the way for every videos. You need the API key, you can get it here: 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

Console Response:

>>>PT6M22S

Corresponds to 6 minutes and 22 seconds.

Second way:


Another way but not works for all videos is with pafy external package:

import pafy

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

I installed pafy from https://pypi.python.org/pypi/pafy/0.3.42

like image 153
Joan Triay Avatar answered Dec 27 '22 17:12

Joan Triay