2008/05/30

追記
最新のWeb::Scraperでは"Web::Scraper::user_agent"でユーザエージェントが変更出来る様になっています。

昨日書いたエントリ「WWW::MechanizeとXPathでtwitterのfriendsを全部取ってみる」のはてなブックマークでotsune氏から
「Web::Scraper/eg/twitter-friends.pl」
というコメントを貰いました。
ただ、この「Web::Scraper/eg/twitter-friends.pl」は、アンカーのrel属性でcontactとなっている物を並べており、私のようなfollowerが少ない人ならばいいのですが、多い人だと100人超えてしまいます。
結果、100人以上取得出来ない事になります。

以上、おしまい!...というのもアレなので...

無理やり感たっぷりですが、Web::Scraperを使ってみました。
ログインしないと、friendsが辿れないのでそこはWWW::Mechanizeに任せ、LWP::UserAgentを継承しているのを利用して、Web::Scraperの__uaを置き換えました。(ウホ!無理やり)
何か他に、キレイなやり方ないですかねぇ...

#!/usr/local/bin/perl

use warnings;
use strict;
use WWW::Mechanize;
use Web::Scraper;
use YAML;

my $username = 'your_username';
my $password = 'your_password';

my $m = WWW::Mechanize->new(timeout => 10);
$m->add_header('Accept-Encoding', 'identity');
$m->get('http://twitter.com/login');
$m->submit_form(
    form_number => 1,
    fields    => {
        username_or_email  => $username,
        password           => $password,
    },
    button    => 'commit',
);

undef &Web::Scraper::__ua;
*Web::Scraper::__ua = sub {
    $m;
};
my $twitter = scraper {
    process 'tr.vcard',
        'friends[]' => scraper {
            process 'td strong a', nick => 'TEXT';
            process 'td.thumb img', image => '@src';
            process 'td.thumb img', name => '@alt';
            process 'td strong a', description => '@title';
            process 'td.thumb a', url => '@href';
        };
    result 'friends';
};

my $num_page = 1;
while (1) {
    my $uri  = URI->new("http://twitter.com/friends/?page=$num_page");
    my $friends = $twitter->scrape($uri);
    %$friends or last;
    $num_page++;
    warn Dump $friends;
}
Posted at 21:31 | WriteBacks () | Edit
Edit this entry...

wikieditish message: Ready to edit this entry.






















A quick preview will be rendered here when you click "Preview" button.