GeniusOfEvil’s Blog

It is a sin to believe evil of others, but it is seldom a mistake.

Archive for the ‘Python’ Category

Howto Get Direct YouTube Video (FLV) URL

with 7 comments

This post is based on paulg’s description of  Youtube video url protocol . Time is precious, so let’s get straight to the point – here’s the Python implementation

import httplib,urllib

video_id = 'PB8pWjMlxxE'
eurl = 'https://geniusofevil.wordpress.com/' #
params = urllib.urlencode({'video_id':video_id, 'eurl':eurl})
conn = httplib.HTTPConnection("www.youtube.com")
conn.request("GET","/get_video_info?&%s"%params)
response = conn.getresponse()
status,reason = response.status, response.reason
data = response.read()
video_info = dict((k,urllib.unquote_plus(v)) for k,v in
                               (nvp.split('=') for nvp in data.split('&')))

Now video_info is a dictionary containing a lot of information about video ( author, length,title, etc) – but we still don’t have direct video URL.

conn.request('GET','/get_video?video_id=%s&t=%s' %
                 ( video_info['video_id'],video_info['token']))
response = conn.getresponse()

YouTube will respond with HTTP 303 See Other

direct_url = response.getheader('location')

Final Solution

# #!/usr/bin/env python  
# # -*- coding: utf-8 -*-

import httplib,urllib
__author__ = 'Jarosław Przygódzki'
__copyright__ = 'Copyright (c) 2009 Jarosław Przygódzki'
__date__ = '30.04.2009'
__license__ = 'GPL'
__version__ = '0.1.1'

def GetYoutubeVideoInfo(videoID,eurl=None):
	'''
	Return direct URL to video and dictionary containing additional info
	>> url,info = GetYoutubeVideoInfo("tmFbteHdiSw")
	>>
	'''
	if not eurl:
		params = urllib.urlencode({'video_id':videoID})
	else :
		params = urllib.urlencode({'video_id':videoID, 'eurl':eurl})
	conn = httplib.HTTPConnection("www.youtube.com")
	conn.request("GET","/get_video_info?&%s"%params)
	response = conn.getresponse()
	data = response.read()
	video_info = dict((k,urllib.unquote_plus(v)) for k,v in 
                               (nvp.split('=') for nvp in data.split('&')))
	conn.request('GET','/get_video?video_id=%s&t=%s' %
                         ( video_info['video_id'],video_info['token']))  
	response = conn.getresponse()
	direct_url = response.getheader('location')
	return direct_url,video_info 

Written by Jarek Przygódzki

April 30, 2009 at 12:07 pm

Posted in Programing, Python