WWW::Mechanizeのテスト

Perlの、簡単にブラウジングを自動化できるライブラリ、WWW::Mechanizeのテスト。TypePadに自動投稿できるかどうかを試してみました。いちおうお仕事。Perlが使えて嬉しいです。

use strict;
use utf8;
use Encode;
binmode STDOUT, ":encoding(shiftjis)";

use Data::Dumper;
$Data::Dumper::Indent = 1;

use WWW::Mechanize;

my $username = '******';
my $password = '******';
my $title = 'title';
my $text = 'text';

my $host = "https://www.typepad.jp";
my $start = $host."/t/app";
my $mech = WWW::Mechanize->new();
$mech->agent_alias('Windows IE 6');

# top
&message('[1]top...');
my $response = $mech->get($start);
&abort(Dumper($response)) unless ($mech->success);

# login フォーム submit
&message('[2]login...');
$mech->form_number(0);
$mech->set_fields('username' => $username, 'password' => $password);
$response = $mech->submit;
&abort(Dumper($response)) unless ($mech->success);

# 新規投稿
&message('[3]post...');
$response = $mech->follow_link(url_regex => qr/t\/app\/weblog\/post\?blog_id/i);
&abort(Dumper($response)) unless ($mech->success);

# 投稿の確認
&message('[4]preview...');
$mech->form_name('entry_form');
$mech->set_fields('title' => $title, 'text' => $text);
$response = $mech->click('preview_entry');
&abort(Dumper($response)) unless ($mech->success);

# 投稿完了
&message('[5]finish...');
$mech->form_number(0);
$response = $mech->click('save');
&abort(Dumper($response)) unless ($mech->success);

# 再構築
&message('[6]rebuild...');
my $report = decode("utf8", $mech->content());
if ($report =~ /window\.location\.replace\('([^\s']+)'\);/) {
    $response = $mech->get(URI->new($host.$1));
    &abort(Dumper($response)) unless ($mech->success);
} else {
    &abort("rebuild error.\n".$report);
}

# 正常終了
&message('successfully finished!');

exit(0);

sub message { 
    foreach (@_) {
        print decode("utf8", $_);
    }
    print "\n";
}

sub abort { &message(@_); exit(1); }

あ、Windowsで開発したので出力はshiftjisになっています。

なんだか最近は、僕の力不足で各方面でいっぱいいっぱいになっています。まぁ、いつものことなんですが。ご迷惑をおかけしている皆様すみません。頑張ります〜。

※ここのサイトが参考になりました→http://digit.que.ne.jp/work/index.cgi?Perl%e3%83%a2%e3%82%b8%e3%83%a5%e3%83%bc%e3%83%ab%2fWWW%3a%3aMechanize