YouTube の mpeg4 を Perl からゲットするよ

| 0 Comments | 1 TrackBack | このエントリーをはてなブックマークに追加 このエントリーのはてなブックマーク件数

こんにちは、自分も perl newbie な yusukebe です。

僕は「ちょっと悪い」 Perl の使い方を紹介したりしようと思っています。

よい子の方々は真似しないでね。


一発目はみんな大好き YouTube に関する Perl スクリプトだよ。

どんなものか簡単に言っちゃうと公開されている YouTube 動画の mpeg4 をダウンロードできるものです。

お好きな YouTube の動画 URL をコマンドライン引数で渡すとよいです。


簡単なコードの解説をします。

ネットにあるものを Perl で取得し利用するのには LWP::UserAgent というモジュールが定番になっています。

最初はそのモジュールを使って、一度 YouTube 動画のページにアクセスします。

my $url = $ARGV[0] || "http://www.youtube.com/watch?v=N7NTRPKfUtw";
my $ua = LWP::UserAgent->new;

my $response = $ua->get($url);
die $response->status_line unless $response->is_success;
my $content = $response->content;

$content という変数にページのデータ(HTMLの文字列)が入るので、正規表現を使って mpeg4 へのURLを構築するためのパラメータを切り出します。その後 mpeg4 へのURLを LWP::UserAgent のオブジェクトに渡しつつ、mirror メソッドでファイルを保存しています。

if($content =~ /video_id=(.+?)&.*?&t=(.+?)&/){
    my $mp4_url = "http://www.youtube.com/get_video?video_id=$1&t=$2&fmt=18";
    warn "downloading mp4 from $mp4_url\n";
    $ua->mirror($mp4_url, "$1.mp4");
}

以下が全部のコードです。LWP::UserAgent の詳細に関しては POD というドキュメントを見てみてください→http://search.cpan.org/dist/libwww-perl/ 。あんまり大声はって言えませんが、「ちょっと悪い」ことをするために Perl が必要だ!となれば、Perl のお勉強が加速すると思っています(現に自分がそうですw)。といわけでまたねー。

#!/usr/bin/perl

use strict;
use warnings;
use LWP::UserAgent;

my $url = $ARGV[0] || "http://www.youtube.com/watch?v=N7NTRPKfUtw";
my $ua = LWP::UserAgent->new;

my $response = $ua->get($url);
die $response->status_line unless $response->is_success;
my $content = $response->content;

if($content =~ /video_id=(.+?)&.*?&t=(.+?)&/){
    my $mp4_url = "http://www.youtube.com/get_video?video_id=$1&t=$2&fmt=18";
    warn "downloading mp4 from $mp4_url\n";
    $ua->mirror($mp4_url, "$1.mp4");
}else{
    warn "Error\n";
}

1 TrackBack

TrackBack URL: http://perl-mongers.org/MT/mt-tb.cgi/22

どんなプログラミング言語でもそうだと思いますが、Perlでは 「使う人」と「作る人」の2種類の人がいると思います。 「使う人」は他の人が作った CPAN モジ... Read More

Leave a comment

About this Entry

This page contains a single entry by yusukebe published on May 26, 2008 11:50 AM.

「Perlベストプラクティス」一通り読んだのでまとめ前半(転載) was the previous entry in this blog.

TYPO - スペルミス is the next entry in this blog.

Find recent content on the main index or look in the archives to find all content.

Categories

Pages

Creative Commons License
This blog is licensed under a Creative Commons License.
Powered by Movable Type 4.21-en