blib/lib/WWW/Crawler/Lite.pm

filter: Statementstmt 56.0% 83 / 148 Branchbran 24.0% 12 / 50 Conditioncond 10.7% 3 / 28 MC/DCmcdc 0.0% 0 / 16 Subroutinesub 60.0% 21 / 35 Podpod 58.8% 10 / 17 totaltotal 43.8% 129 / 294 CC 36 SCAR 35.7
CC
36
Cov
43%
_parse_result
145.2
__ANON__
20.0
crawl
15.0
CRAP 35.7
↑ Summary
1 package WWW::Crawler::Lite;
2  
3 2 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 2 ▶use warnings 'all';
Subroutine BEGIN: called CC=1 SCAR=0.0
5 2 ▶use LWP::UserAgent;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 2 ▶use HTTP::Request::Common;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 2 ▶use WWW::RobotRules;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 2 ▶use URI::URL;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 2 ▶use HTML::LinkExtor;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 2 ▶use Time::HiRes 'usleep';
Subroutine BEGIN: called CC=1 SCAR=0.0
11 2 ▶use Carp 'confess';
Subroutine BEGIN: called CC=1 SCAR=0.0
12  
13 2 our $VERSION = '0.005';
14  
15  
16 sub new
17 1 ▶{
Subroutine new: called CC=1 SCAR=1.2
Pod documented
18 1 my ($class, %args) = @_;
19
20 my $s = bless {
21 url_pattern => 'https?://.+',
22 agent => "WWW-Crawler-Lite/$VERSION $^O",
23 http_accept => [qw( text/html text/plain application/xhtml+xml )],
24 1 ▶ on_new_urls => sub { my @urls = @_; },
Subroutine __ANON__: called CC=1 SCAR=0.0
25 0 ▶ on_bad_url => sub { my ($bad_url) = @_; },
Subroutine __ANON__: not called CC=1 SCAR=6.9
26 0 ▶ on_response => sub { my ($url, $http_response) = @_; },
Subroutine __ANON__: not called CC=1 SCAR=6.9
27 0 ▶ on_link => sub { my ($from, $to, $text) = @_ },
Subroutine __ANON__: not called CC=1 SCAR=6.9
28 0 ▶ follow_ok => sub { my ($url) = @_; return 1; },
Subroutine __ANON__: not called CC=1 SCAR=6.9
29 1 link_parser => 'default',
30 delay_seconds => 1,
31 disallowed => [ ],
32 %args,
33 urls => { },
34 _responded_urls => { },
35 RUNNING => 1,
36 IS_INITIALIZING => 1,
37 }, $class;
38 1 $s->{rules} = WWW::RobotRules->new( $s->agent );
39
40 1 return $s;
41 }# end new()
42  
43 # Public read-only properties:
44 2 ▶sub agent { shift->{agent} }
Subroutine agent: called CC=1 SCAR=0.0
Pod documented
45 2 ▶sub url_pattern { shift->{url_pattern} }
Subroutine url_pattern: called CC=1 SCAR=0.0
Pod documented
46 0 ▶sub delay_seconds { shift->{delay_seconds} }
Subroutine delay_seconds: not called CC=1 SCAR=6.9
Pod documented
47 3 ▶sub http_accept { @{ shift->{http_accept} } }
Subroutine http_accept: called CC=1 SCAR=0.0
Pod documented
48 0 ▶sub is_initializing { shift->{IS_INITIALIZING} }
Subroutine is_initializing: not called CC=1 SCAR=6.9
Pod undocumented
49 0 ▶sub is_running { shift->{RUNNING} }
Subroutine is_running: not called CC=1 SCAR=6.9
Pod undocumented
50 0 ▶sub rules { shift->{rules} }
Subroutine rules: not called CC=1 SCAR=6.9
Pod undocumented
51  
52 # Public method:
53 0 ▶sub stop { shift->{RUNNING} = 0 }
Subroutine stop: not called CC=1 SCAR=6.9
Pod documented
54  
55  
56 # Public getters/setters:
57 sub on_new_urls
58 1 ▶{
Subroutine on_new_urls: called CC=2 SCAR=7.2
Pod undocumented
59 1 my $s = shift;
60
61 1 ▶ return @_ ? $s->{on_new_urls} = shift : $s->{on_new_urls};
Branch: 1 branch
BranchTrueFalseTotal
@_ ? : 0 1 1
62 }# end on_new_urls()
63  
64 sub on_bad_url
65 0 ▶{
Subroutine on_bad_url: not called CC=2 SCAR=17.9
Pod documented
66 0 my $s = shift;
67
68 0 ▶ return @_ ? $s->{on_bad_url} = shift : $s->{on_bad_url};
Branch: 1 branch
BranchTrueFalseTotal
@_ ? : 0 0 0
69 }# end on_bad_url()
70  
71 sub on_response
72 1 ▶{
Subroutine on_response: called CC=2 SCAR=7.2
Pod documented
73 1 my $s = shift;
74
75 1 ▶ return @_ ? $s->{on_response} = shift : $s->{on_response};
Branch: 1 branch
BranchTrueFalseTotal
@_ ? : 0 1 1
76 }# end on_response()
77  
78 sub on_link
79 0 ▶{
Subroutine on_link: not called CC=2 SCAR=17.9
Pod documented
80 0 my $s = shift;
81
82 0 ▶ return @_ ? $s->{on_link} = shift : $s->{on_link};
Branch: 1 branch
BranchTrueFalseTotal
@_ ? : 0 0 0
83 }# end on_link()
84  
85  
86 sub follow_ok
87 0 ▶{
Subroutine follow_ok: not called CC=2 SCAR=17.9
Pod undocumented
88 0 my $s = shift;
89  
90 0 ▶ return @_ ? $s->{follow_ok} = shift : $s->{follow_ok};
Branch: 1 branch
BranchTrueFalseTotal
@_ ? : 0 0 0
91 }# end follow_ok()
92  
93  
94 sub link_parser
95 2 ▶{
Subroutine link_parser: called CC=2 SCAR=7.2
Pod documented
96 2 my $s = shift;
97  
98 2 ▶ return @_ ? $s->{link_parser} = shift : $s->{link_parser};
Branch: 1 branch
BranchTrueFalseTotal
@_ ? : 0 2 2
99 }# end link_parser()
100  
101  
102 sub url_count
103 0 ▶{
Subroutine url_count: not called CC=1 SCAR=6.9
Pod undocumented
104 0 my ($s) = @_;
105
106 0 return scalar( keys %{ $s->{urls} } );
107 }# end url_count()
108  
109  
110 sub crawl
111 1 ▶{
Subroutine crawl: called CC=9 SCAR=27.1
Pod undocumented
112 1 my ($s, %args) = @_;
113
114 1 ▶ confess "Require param 'url' not provided" unless $args{url};
Branch: 1 branch
BranchTrueFalseTotal
unless $args{"url"} 0 1 1
115
116 1 my $ua = LWP::UserAgent->new( agent => $s->agent );
117 3 ▶ $ua->add_handler( response_header => sub {
Subroutine __ANON__: called CC=4 SCAR=14.9
118 3 my ($response, $ua, $h) = @_;
119 3 ▶ my ($type) = split /\;/, ( $response->header('content-type') || '' )
Branch: 1 branch
BranchTrueFalseTotal
my($type) = split(/\;/, $response->header("content-type") || "", 2) or die "no mime type provided by server" 3 0 3
Condition50%1/2
$response->header('content-type') || ''
l!l
30
MC/DC0%0/1
$response->header('content-type') || ''
$response->header('content-type')
Truth table50%1/2
A
A= $response->header('content-type')
Aresult
11
00
120 or die "no mime type provided by server";
121 3 ▶ grep { $type =~ m{\Q$_\E}i } $s->http_accept
Branch: 1 branch
BranchTrueFalseTotal
grep {$type =~ /\Q$_\E/i;} $s->http_accept or die "unwanted mime type '${type}'" 3 0 3
122 or die "unwanted mime type '$type'";
123 1 });
124  
125 # Try to find robots.txt:
126 1 my ($proto, $domain) = $args{url} =~ m{^(https?)://(.*?)(?:/|$)};
127 1 eval {
128 1 local $SIG{__DIE__} = \&confess;
129 1 my $robots_url = "$proto://$domain/robots.txt";
130 1 my $res = $ua->request( GET $robots_url );
131
132 # If robots.txt has extra newlines in it, the rules parser always allows (which is bad):
133 1 (my $robots_txt = $res->content) =~ s/[\r?\n]{2,}/\n/sg;
134 1 ▶ $s->rules->parse( $robots_url, $robots_txt )
Branch: 1 branch
BranchTrueFalseTotal
if $res and $res->is_success and $res->content 0 1 1
Condition33%2/6
$res and $res->is_success and $res->content
!ll&&!rl&&r
100
$res and $res->is_success
!ll&&!rl&&r
010
MC/DC0%0/3
$res and $res->is_success and $res->content
$res $res->is_success $res->content
Truth table25%1/4
A and B and C
A= $resB= $res->is_successC= $res->content
ABCresult
0XX0
10X0
1100
1111
135 if $res && $res->is_success && $res->content;
136 };
137 1 ▶ warn "Error fetching/parsing robots.txt: $@" if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 0 1 1
138
139 1 $s->{urls}->{$args{url}} = 'taken';
140 1 my $res = $ua->request( GET $args{url} );
141 1 $s->_parse_result( $args{url}, $res );
142
143 1 ▶ while( my $url = $s->_take_url() )
Branch: 1 branch
BranchTrueFalseTotal
if (my $url = $s->_take_url) 0 1 1
144 {
145 0 usleep( $s->delay_seconds * 1_000_000 );
146 0 ▶ last unless $s->is_running;
Branch: 1 branch
BranchTrueFalseTotal
unless $s->is_running 0 0 0
147
148 0 my $res = $ua->request( GET $url );
149 0 my ($type) = split /\;/, $res->header('content-type');
150
151 # Only parse responses that are of the correct MIME type:
152 $s->_parse_result( $url, $res )
153 0 ▶ if grep { $type =~ m{\Q$_\E}i } $s->http_accept;
Branch: 1 branch
BranchTrueFalseTotal
if grep {$type =~ /\Q$_\E/i;} $s->http_accept 0 0 0
154 }# end while()
155 }# end crawl()
156  
157  
158 sub _take_url
159 1 ▶{
Subroutine _take_url: called CC=2 SCAR=7.8
160 1 my ($s) = @_;
161
162 1 my $url;
163 SCOPE: {
164 0 ▶ ($url) = grep { $s->rules->allowed( $_ ) } grep { $s->{urls}->{$_} eq 'new' } keys %{ $s->{urls} }
Branch: 1 branch
BranchTrueFalseTotal
($url) = grep({$s->rules->allowed($_);} grep({$s->{"urls"}{$_} eq "new";} keys %{$$s{"urls"};})) or return 0 1 1
165 or return;
166 0 $s->{urls}->{$url} = 'taken';
167 };
168 0 return $url;
169 }# end _take_url()
170  
171  
172 sub _parse_result
173 1 ▶{
Subroutine _parse_result: called CC=15 SCAR=49.8
174 1 my ($s, $url, $res) = @_;
175
176 1 my $base = $res->base;
177 1 my @new_urls = ( );
178  
179 1 ▶ if( $s->link_parser eq 'HTML::LinkExtor' )
Branch: 2 branches
BranchTrueFalseTotal
if ($s->link_parser eq 'HTML::LinkExtor') { } 0 1 1
elsif ($s->link_parser eq 'default') { } 1 0 1
180 {
181 # This option added after the original regexp way was pointed out on perlmonks:
182 # http://www.perlmonks.org/?node_id=946548
183 0 ▶ my $cb = sub {
Subroutine __ANON__: not called CC=4 SCAR=30.0
184 0 my ($tag, %attrs) = @_;
185 0 ▶ return unless uc($tag) eq 'A';
Branch: 1 branch
BranchTrueFalseTotal
unless uc $tag eq "A" 0 0 0
186 0 ▶ if( $s->follow_ok->( $attrs{href} ) )
Branch: 1 branch
BranchTrueFalseTotal
if ($s->follow_ok->($attrs{"href"})) 0 0 0
187 {
188 0 ▶ push @new_urls, { href => $attrs{href}, text => $attrs{title} || $attrs{alt} };
Condition0%0/3
$attrs{'title'} || $attrs{'alt'}
l!l&&r!l&&!r
000
MC/DC0%0/2
$attrs{'title'} || $attrs{'alt'}
$attrs{'title'} $attrs{'alt'}
Truth table0%0/3
A || B
A= $attrs{'title'}B= $attrs{'alt'}
ABresult
1X1
011
000
189 }# end if()
190 0 };
191 0 my $parser = HTML::LinkExtor->new($cb, $base);
192 0 $parser->parse( $res->content );
193 }
194 elsif( $s->link_parser eq 'default' )
195 {
196 # This method might be a bit naive, but HTML::LinkExtor (AFAIK) doesn't allow
197 # me to get at the text within a hyperlink.
198 # I'm open to alternatives and recognise the problems inherent in parsing
199 # HTML with regexps.
200 1 (my $tmp = $res->content) =~ s{<a\s+.*?href\s*\=(.*?)>(.*?)</a>}{
201 0 my ($href,$anchortext) = ( $1, $2 );
202 0 ▶ if( $anchortext =~ m/<img/ )
Branch: 1 branch
BranchTrueFalseTotal
if ($anchortext =~ /<img/) 0 0 0
203 {
204 0 my ($alt) = join ". ", $anchortext =~ m/alt\s*\=\s*"(.*?)"/sig;
205 0 $anchortext =~ s/<img.*?>//sig;
206 0 ▶ $anchortext .= ". $alt" if $alt;
Branch: 1 branch
BranchTrueFalseTotal
if $alt 0 0 0
207 }# end if()
208 0 $anchortext =~ s{</?.*?[/>]}{}sg;
209 0 ▶ if( my ($quote) = $href =~ m/^(['"])/ )
Branch: 1 branch
BranchTrueFalseTotal
if (my($quote) = $href =~ /^(['"])/) { } 0 0 0
210 {
211 0 ($href) = $href =~ m/^$quote(.*?)$quote/;
212 }
213 else
214 {
215 0 ($href) = $href =~ m/^([^\s+])/;
216 }# end if()
217 0 ▶ $href = "" unless defined($href);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $href 0 0 0
218 0 $href =~ s/\#.*$//;
219 0 ▶ if( $href )
Branch: 1 branch
BranchTrueFalseTotal
if ($href) 0 0 0
220 {
221 0 (my $new = url($href, $base)->abs->as_string) =~ s/\#.*$//;
222 0 ▶ if( $s->follow_ok->( $new ) )
Branch: 1 branch
BranchTrueFalseTotal
if ($s->follow_ok->($new)) 0 0 0
223 {
224 0 $anchortext =~ s/^\s+//s;
225 0 $anchortext =~ s/\s+$//s;
226 0 push @new_urls, { href => $new, text => $anchortext };
227 }# end if()
228 }# end if()
229 0 "";
230 }isgxe;
231 }# end if()
232
233 1 $s->on_response->( $url, $res );
234  
235 1 my %accepted_urls = ( );
236 SCOPE: {
237 1 my $pattern = $s->url_pattern;
238 map {
239 0 $accepted_urls{$_}++;
240 0 ▶ $s->{urls}->{$_} ||= 'new';
Condition0%0/2
$s->{"urls"}{$_} ||= "new"
l!l
00
MC/DC0%0/1
$s->{"urls"}{$_} ||= "new"
$s->{"urls"}{$_}
Truth table0%0/2
A
A= $s->{"urls"}{$_}
Aresult
11
00
241 }
242 grep {
243 0 my $u = $_;
244 m/$pattern/ &&
245 ! exists($s->{urls}->{$u}) &&
246 ! grep {
247 0 ▶ $u =~ m{^https?://[^/]+?\Q$_\E.*}
Condition0%0/3
@{$s->{'disallowed'};} && $s->rules->allowed($u)
!ll&&!rl&&r
000
MC/DC0%0/2
@{$s->{'disallowed'};} && $s->rules->allowed($u)
@{$s->{'disallowed'};} $s->rules->allowed($u)
Truth table0%0/3
A && B
A= @{$s->{'disallowed'};}B= $s->rules->allowed($u)
ABresult
0X0
100
111
248 0 ▶ } @{$s->{disallowed}} &&
Condition0%0/6
/$pattern/ && !exists $s->{'urls'}{$u} && !grep({$u =~ m[^https?://[^/]+?\Q$_\E.*];} @{$s->{'disallowed'};} && $s->rules->allowed($u))
!ll&&!rl&&r
000
/$pattern/ and not exists $s->{"urls"}{$u}
!ll&&!rl&&r
000
MC/DC0%0/3
/$pattern/ && !exists $s->{'urls'}{$u} && !grep({$u =~ m[^https?://[^/]+?\Q$_\E.*];} @{$s->{'disallowed'};} && $s->rules->allowed($u))
/$pattern/ not exists $s->{"urls"}{$u} !grep({$u =~ m[^https?://[^/]+?\Q$_\E.*];} @{$s->{'disallowed'};} && $s->rules->allowed($u))
Truth table0%0/4
A and not(B) && not(C)
A= /$pattern/B= not exists $s->{"urls"}{$u}C= !grep({$u =~ m[^https?://[^/]+?\Q$_\E.*];} @{$s->{'disallowed'};} && $s->rules->allowed($u))
ABCresult
0XX0
10X0
1100
1111
249 $s->rules->allowed( $u )
250 }
251 0 map { $_->{href} } @new_urls;
252 };
253
254 # Send the event about this page linking to those other pages:
255 1 my $pattern = $s->url_pattern;
256 map {
257 0 $s->on_link->( $url, $_->{href}, $_->{text} );
258 }
259 grep {
260 0 my $u = $_;
261 $u->{href} =~ m/$pattern/ &&
262 ! grep {
263 0 ▶ $u->{href} =~ m{^https?://[^/]+?\Q$_\E.*}
Condition0%0/3
@{$s->{'disallowed'};} && $s->rules->allowed($u->{'href'})
!ll&&!rl&&r
000
MC/DC0%0/2
@{$s->{'disallowed'};} && $s->rules->allowed($u->{'href'})
@{$s->{'disallowed'};} $s->rules->allowed($u->{'href'})
Truth table0%0/3
A && B
A= @{$s->{'disallowed'};}B= $s->rules->allowed($u->{'href'})
ABresult
0X0
100
111
264 0 } @{$s->{disallowed}} &&
265 $s->rules->allowed( $u->{href} )
266 0 ▶ } @new_urls;
Condition0%0/3
$u->{'href'} =~ /$pattern/ && !grep({$u->{'href'} =~ m[^https?://[^/]+?\Q$_\E.*];} @{$s->{'disallowed'};} && $s->rules->allowed($u->{'href'}))
!ll&&!rl&&r
000
MC/DC0%0/2
$u->{'href'} =~ /$pattern/ && !grep({$u->{'href'} =~ m[^https?://[^/]+?\Q$_\E.*];} @{$s->{'disallowed'};} && $s->rules->allowed($u->{'href'}))
$u->{'href'} =~ /$pattern/ !grep({$u->{'href'} =~ m[^https?://[^/]+?\Q$_\E.*];} @{$s->{'disallowed'};} && $s->rules->allowed($u->{'href'}))
Truth table0%0/3
A && not(B)
A= $u->{'href'} =~ /$pattern/B= !grep({$u->{'href'} =~ m[^https?://[^/]+?\Q$_\E.*];} @{$s->{'disallowed'};} && $s->rules->allowed($u->{'href'}))
ABresult
0X0
100
111
267  
268 1 $s->on_new_urls->( keys(%accepted_urls) );
269 }# end _parse_result()
270  
271 2 1;# return true:
272  
273 =pod
274  
275 =head1 NAME
276  
277 WWW::Crawler::Lite - A single-threaded crawler/spider for the web.
278  
279 =head1 SYNOPSIS
280  
281 my %pages = ( );
282 my $pattern = 'https?://example\.com\/';
283 my %links = ( );
284 my $downloaded = 0;
285  
286 my $crawler;
287 $crawler = WWW::Crawler::Lite->new(
288 agent => 'MySuperBot/1.0',
289 url_pattern => $pattern,
290 http_accept => [qw( text/plain text/html application/xhtml+xml )],
291 link_parser => 'default',
292 on_response => sub {
293 my ($url, $res) = @_;
294  
295 warn "$url contains " . $res->content;
296 $downloaded++;
297 $crawler->stop() if $downloaded++ > 5;
298 },
299 follow_ok => sub {
300 my ($url) = @_;
301 # If you like this url and want to use it, then return a true value:
302 return 1;
303 },
304 on_link => sub {
305 my ($from, $to, $text) = @_;
306  
307 return if exists($pages{$to}) && $pages{$to} eq 'BAD';
308 $pages{$to}++;
309 $links{$to} ||= [ ];
310 push @{$links{$to}}, { from => $from, text => $text };
311 },
312 on_bad_url => sub {
313 my ($url) = @_;
314  
315 # Mark this url as 'bad':
316 $pages{$url} = 'BAD';
317 }
318 );
319 $crawler->crawl( url => "http://example.com/" );
320  
321 warn "DONE!!!!!";
322  
323 use Data::Dumper;
324 map {
325 warn "$_ ($pages{$_} incoming links) -> " . Dumper($links{$_})
326 } sort keys %links;
327  
328 =head1 DESCRIPTION
329  
330 C<WWW::Crawler::Lite> is a single-threaded spider/crawler for the web. It can
331 be used within a mod_perl, CGI or Catalyst-style environment because it does not
332 fork or use threads.
333  
334 The callback-based interface is fast and simple, allowing you to focus on simply
335 processing the data that C<WWW::Crawler::Lite> extracts from the target website.
336  
337 =head1 PUBLIC METHODS
338  
339 =head2 new( %args )
340  
341 Creates and returns a new C<WWW::Crawler::Lite> object.
342  
343 The C<%args> hash is not required, but may contain the following elements:
344  
345 =over 4
346  
347 =item agent - String
348  
349 Used as the user-agent string for HTTP requests.
350  
351 B<Default Value:> - C<WWW-Crawler-Lite/$VERSION $^O>
352  
353 =item url_pattern - RegExp or String
354  
355 New links that do not match this pattern will not be added to the processing queue.
356  
357 B<Default Value:> C<https?://.+>
358  
359 =item http_accept - ArrayRef
360  
361 This can be used to filter out unwanted responses.
362  
363 =item link_parser - String
364  
365 Valid values: 'C<default>' and 'C<HTML::LinkExtor>'
366  
367 The default value is 'C<default>' which uses a naive regexp to do the link parsing.
368  
369 The upshot of using 'C<default>' is that the regexp will also find the hyperlinked
370 text or alt-text (of a hyperlinked img tag) and give that to your 'C<on_link>' handler.
371  
372 B<Default Value:> C<[qw( text/html text/plain application/xhtml+xml )]>
373  
374 =item on_response($url, $response) - CodeRef
375  
376 Called whenever a successful response is returned.
377  
378 =item on_link($from, $to, $text) - CodeRef
379  
380 Called whenever a new link is found. Arguments are:
381  
382 =over 8
383  
384 =item $from
385  
386 The URL that is linked *from*
387  
388 =item $to
389  
390 The URL that is linked *to*
391  
392 =item $text
393  
394 The anchor text (eg: The HTML within the link - <a href="...">B<This Text Here></a>)
395  
396 =back
397  
398 =item on_bad_url($url) - CodeRef
399  
400 Called whenever an unsuccessful response is received.
401  
402 =item delay_seconds - Number
403  
404 Indicates the length of time (in seconds) that the crawler should pause before making
405 each request. This can be useful when you want to spider a website, not launch
406 a denial of service attack on it.
407  
408 =back
409  
410 =head2 stop( )
411  
412 Causes the crawler to stop processing its queue of URLs.
413  
414 =head1 AUTHOR
415  
416 John Drago <jdrago_999@yahoo.com>
417  
418 =head1 COPYRIGHT
419  
420 This software is Free software and may be used and redistributed under the same
421 terms as perl itself.
422  
423 =cut
424  
425  
426  
↑ Summary