Youtube Video Downloader in Ruby
#Written by Cheng Meng
#Created on 2007-7-27
require ‘open-uri‘
url_video = ""
youtube = "http://www.youtube.com/"
ARGV[0] =~ /(?:#{youtube}(?:watch\\?v=|v\\/))?(.*)$/
video_id = $1
open("#{youtube}watch\\?v=#{video_id}") do |f|
f.each_line do |line|
if line =~ /SWFObject\\("\\/player2.swf\\?([^"]+)"/
url_video << "#{youtube}get_video?#{$1}"
break
end
end
end
#puts "video:#{url_video}"
video = File.new("video_#{video_id}.flv","wb")
open(url_video) do |f|
f.each_byte { |c| video.putc c }
end
This program is based on the idea explained in Peteris Krumins’s article Downloading Youtube videos with gawk.But I don’t know any gawk(巨拗口,in Chinese),and I just learn a little Ruby.So I decided to hack my own.
usage:save the above code as .rb file.This program accepts one argument to specify the url of the youtube video page.Three forms of urls are all permitted:the watch page,such as http://www.youtube.com/watch?v=En0A8KGMgq8,or http://www.youtube.com/v/En0A8KGMgq8,which usually contained in embedded code;even just the ID,En0A8KGMgq8,is OK.Then the script parses the argument,finds the actual url of video,and saves video to a “video_ID.flv” file.
Note:Linux users may need to change the mode option “wb” to “w”(I’m not sure about this,for I have not a linux system in my laptop).Only DOS/Windows needs this “b” to prevent Ruby from converting ‘\a’ to ‘\d\a’.I waste a lot of time in this problem.
Update:according to Corsair,the task of downloading should be given to more professional tools,such as wget.Just remove the last 3 lines and add “puts url_video”.Use pipe to connect my script to wget,like this:
wget -O output_filename `video_downloader.rb url`
video_downloader.rb is the modified script.
阅读(1109 次)