在this後我得知在該特定示例中,Ruby/Perl中的Mechanize
比HTML::TreeBuilder 3
更易於使用。機械化可以使這變得更容易嗎?
是Mechanize
優於HTML::TokeParser
?
下面在使用Mechanize
的Ruby中編寫代碼是否更容易?
sub get_img_page_urls {
my $url = shift;
my $ua = LWP::UserAgent->new;
$ua->agent("$0/0.1 " . $ua->agent);
$ua->agent("Mozilla/8.0");
my $req = new HTTP::Request 'GET' => "$url";
$req->header('Accept' => 'text/html');
$response_u = $ua->request($req); # send request
die "Error: ", $response_u->status_line unless $response_u->is_success;
my $stream = HTML::TokeParser->new(\$response_u->content);
my %urls =();
my $found_thumbnails = 0;
my $found_thumb = 0;
while (my $token = $stream->get_token) {
# <div class="thumb-box" ... >
if ($token->[0] eq 'S' and $token->[1] eq 'div' and $token->[2]{class} eq 'thumb-box') {
$found_thumbnails = 1;
}
# <div class="thumb" ... >
if ($token->[0] eq 'S' and $token->[1] eq 'div' and $token->[2]{class} eq 'thumb') {
$found_thumb = 1;
}
# <a ... >
if ($found_thumbnails and $found_thumb and $token->[0] eq 'S' and $token->[1] eq 'a') {
$urls{'http://example.com' . "$token->[2]{href}"} = 1;
# one url have been found. Now start all over.
$found_thumb = 0;
$found_thumbnails = 0;
}
}
return %urls;
}
我注意到的第一件事是,你應該使用真/假,而不是1/0,因爲在Ruby中0的值爲true的習慣得到。 – pguardiario
這與您的其他問題幾乎完全相同。機械化不是解析器,所以你不能將它與TokeParser進行比較。 (但恕我直言,任何現代的DOM解析器都會比TokeParser更優秀)。是的,使用Ruby編寫代碼比較容易,無論是否使用Mechanize。 (這個代碼在Perl中也可以更簡單BTW) –