SpringerLink eBooks ダウンローダー

SpringerLinkのebookは1章ずつしかダウンロードできないので面倒。全章ダウンロードして1つのPDFファイルに結合するまで自動で行うプログラムを作った。

#!/usr/bin/perl
# slinkdown.pl
use strict;
use warnings;
use Getopt::Long;
use Web::Scraper;
use WWW::Mechanize;
use CAM::PDF;

my $baseURL = 'http://www.springerlink.com/content/';
my $contentsPageURL;
# 引数がISBNならそれからcontents page URLを作成
# 引数がcontents page URLならそれをそのまま使用
if($ARGV[0] =~ /^[0-9]/){
	$contentsPageURL = $baseURL . $ARGV[0] . "/contents";
}else{
	$contentsPageURL = $ARGV[0];
}

# -t, -cオプションを取得
my $opt_title = 0;
my $opt_concat = 0;
GetOptions('title=s' => \$opt_title, 'concat' => \$opt_concat);

# -tオプションでタイトルを明示できる
# さもなくば自動で取得
my $title;
if($opt_title){
	$title = $opt_title;
}else{
	my $scraper = scraper { process '//h1[@class="title"]', 'title' => 'text'; };
	my $uri = new URI("$contentsPageURL");
	my $res = $scraper->scrape($uri);
	$title = $res->{title};
	$title =~ s/^\s+//;
	$title =~ s/\s+$//;
}

# タイトル名のフォルダを作る
mkdir "./$title";
chdir "$title";

# 各章のURLを配列に記憶
my $mech = WWW::Mechanize->new( agent => "" );
$mech->get("$contentsPageURL");
my @pdfURLs = $mech->find_all_links( text_regex => qr/Download PDF/ );

# リネームしながらダウンロード
my $chapterNum = 1;
foreach(@pdfURLs){
	$chapterNum = sprintf "%02d", $chapterNum;
	my $pdf = $_->url_abs();
	`wget -U "" -O ${chapterNum}.pdf $pdf`;
	$chapterNum++;
	
	sleep 5;
}

# -cオプションで結合
if($opt_concat){ `pdftk *.pdf cat output "${title}.pdf"`; }

使い方:perl slinkdown.pl [-t Title] [-c]

↓ISBNで指定する場合。

% perl slinkdown.pl 978-1-59059-239-7 -c


↓SpringerLink上のURLで指定する場合。ドイツ語のタイトルを英語に変更してみた。

% perl slinkdown.pl http://www.springerlink.com/content/978-3-642-04717-6/contents/ -t "Haskell-intensive course -- A compact introduction to functional programming (German)" -c


参考:
http://milianw.de/code-snippets/download-script-for-springerlinkcom-ebooks
http://c-aurich.de/wordpress/software/springerlink-batchcreator/