Monday, February 18, 2008

Downloading youtube videos into FLV / Divx formats

This script was slightly modified from the older version which was taken from http://www.perlmonks.org/?node_id=570467
You need to have PERL, wget and mencoder installed to run this. Can be done from either Windows/Unix environment.
(If you do not know how to set up these in Windows, I will explain it in another entry)
 
Usage:
1. First create a file called "list" which contains a list of youtube URLs to be downloaded
2. In the command line type "perl <this file>"
 
Working:
An FLV file as well as the converted AVI file (in Divx format) are stored in the current directory
 
#!/usr/bin/perl
use warnings;
use LWP::Simple;
use LWP::UserAgent;
open(FPLIST,"list") || die("cant open list\n");
while(<FPLIST>) {
   chomp($_);
   $link = $_;
   # shamelessly reversed engineered from a python script :-)
  
   print "startring first page retrieval : $link\n";
   my $urlin  = shift || $link;
   my $content = get( $urlin  ) or die "$!\n";
   print "done first page retrieval\n";
  
   # regex for 2 key text strings which identify the video file
   # the second one $2 is unique for each download attempt
   $content =~ /watch_fullscreen.*video_id=([^&]+)&.*t=([^&]+)&/ ;
  
   print $1, "\n" , $2, "\n"; 
   my $file=$1;
   my $infile = $file.'.flv';  #add a .flv extension
  
   print "gettin video file $get_url\n";
   system("wget -O $infile \"http://www.youtube.com/get_video?video_id=$1&t=$2\"");
  
   #convert the FLV file to Divx AVI
   system( "mencoder  $infile -oac mp3lame -ovc lavc -ffourcc DX50 -o $file.avi" );
}

No comments: