Youtube Video URL Extractor in Python
By mw
@
#!/usr/bin/env python # Time-stamp: <corsair 2007-07-28 16:16:38> # Corsair <[email protected]> # Usage: youtube-url video-id import sys import urllib2 import getopt
def main(): # Options parsing, fake for now. try: Options, Args = getopt.gnu_getopt(sys.argv[1:], "", []) except getopt.GetoptError: # print help information and exit: pass
<span class="keyword">if</span> len(sys.argv) == 1:
<span class="keyword">print</span> <span class="string">"Pleas specify a video-id."</span>
sys.exit(1)
VideoID = sys.argv[1]
WatchPage = urllib2.urlopen(
<span class="string">""</span>.join([<span class="string">"http://youtube.com/watch?v="</span>, VideoID]))
HtmlLine = <span class="string">""</span>
<span class="keyword">while</span> HtmlLine.find(<span class="string">"SWFObject"</span>) == -1:
HtmlLine = WatchPage.readline()
UrlOriginal = HtmlLine[HtmlLine.find(<span class="string">"BASE_YT_URL"</span>)+12:]
UrlOriginal = <span class="string">'?'</span>.join([<span class="string">"http://www.youtube.com/get_video"</span>,
UrlOriginal[:UrlOriginal.find(<span class="string">'\"'</span>)].
partition(<span class="string">'&'</span>)[2]])
<span class="comment"># Redirect
RedirectOpener = urllib2.build_opener( urllib2.HTTPRedirectHandler) Request = urllib2.Request(UrlOriginal) UrlReal = RedirectOpener.open(Request).url print UrlReal
if name == "main": main()