Sky Watch

Youtube Video URL Extractor in Python

看到了 Cheng Meng 的那个 Youtube downloader,由于对 Ruby 的无知,一点也看不懂,所以就参考 DownloadYoutube video with GAWK 用 python 自己写了一个。与 Cheng Meng 那个不同,我这个只负责把视频文件 url 打印出来。用法是 video-id 所以要下载 id为 `qNKtKm3SXvs` 的视频,可以用这个命令

wget -O video.flv qNKtKm3SXvs 的代码:

#!/usr/bin/env python # Time-stamp: <corsair 2007-07-28 16:16:38> # Corsair <> # 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>

VideoID = sys.argv[1]
WatchPage = urllib2.urlopen(
    <span class="string">""</span>.join([<span class="string">""</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">""</span>,
                        UrlOriginal[:UrlOriginal.find(<span class="string">'\"'</span>)].
                        partition(<span class="string">'&amp;'</span>)[2]])

<span class="comment"># Redirect

RedirectOpener = urllib2.build_opener( urllib2.HTTPRedirectHandler) Request = urllib2.Request(UrlOriginal) UrlReal = print UrlReal

if name == "main": main()