lib/WWW/Crawler/Mojo.pm

filter: Statementstmt 85.9% 116 / 135 Branchbran 71.1% 37 / 52 Conditioncond 82.3% 14 / 17 MC/DCmcdc 72.7% 8 / 11 Subroutinesub 82.7% 24 / 29 Podpod 100% 8 / 8 totaltotal 82.1% 207 / 252 CC 36 SCAR 16.4
CC
36
Cov
82%
crawl
12.0
scrape
10.0
_make_child
9.0
CRAP 5.2
« blib/lib/WWW/Crawler/Mojo/Queue/MySQL.pm ↑ Summary lib/WWW/Crawler/Mojo/Job.pm »
1 package WWW::Crawler::Mojo;
2 10 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
3 10 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 10 ▶use Mojo::Base 'Mojo::EventEmitter';
Subroutine BEGIN: called CC=1 SCAR=0.0
5 10 ▶use WWW::Crawler::Mojo::Job;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 10 ▶use WWW::Crawler::Mojo::Queue::Memory;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 10 ▶use WWW::Crawler::Mojo::UserAgent;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 10 ▶use WWW::Crawler::Mojo::ScraperUtil qw{
Subroutine BEGIN: called CC=1 SCAR=0.0
9 10 collect_urls_css html_handler_presets reduce_html_handlers resolve_href decoded_body};
10 10 ▶use Mojo::Message::Request;
Subroutine BEGIN: called CC=1 SCAR=0.0
11 10 our $VERSION = '0.26';
12  
13 10 has clock_speed => 0.25;
14 16 ▶has html_handlers => sub { html_handler_presets() };
Subroutine __ANON__: called CC=1 SCAR=0.0
15 10 has max_conn => 1;
16 10 has max_conn_per_host => 1;
17 15 ▶has queue => sub { WWW::Crawler::Mojo::Queue::Memory->new };
Subroutine __ANON__: called CC=1 SCAR=0.0
18 10 has 'shuffle';
19 13 ▶has ua => sub { WWW::Crawler::Mojo::UserAgent->new };
Subroutine __ANON__: called CC=1 SCAR=0.0
20 10 has ua_name =>
21 "www-crawler-mojo/$VERSION (+https://github.com/jamadam/www-crawler-mojo)";
22  
23 0 ▶sub crawl {
Subroutine crawl: not called CC=3 SCAR=24.8
Pod documented
24 0 my ($self) = @_;
25  
26 0 $self->init;
27  
28 0 ▶ die 'No job is given' unless ($self->queue->length);
Branch: 1 branch
BranchTrueFalseTotal
unless $self->queue->length 0 0 0
29  
30 0 $self->emit('start');
31  
32 0 ▶ Mojo::IOLoop->start unless Mojo::IOLoop->is_running;
Branch: 1 branch
BranchTrueFalseTotal
unless "Mojo::IOLoop"->is_running 0 0 0
33 }
34  
35 12 ▶sub init {
Subroutine init: called CC=5 SCAR=17.2
Pod documented
36 12 my ($self) = @_;
37  
38 2 ▶ $self->on('empty', sub { say "Queue is drained out."; $self->stop })
Subroutine __ANON__: called CC=1 SCAR=0.0
39 12 ▶ unless $self->has_subscribers('empty');
Branch: 1 branch
BranchTrueFalseTotal
unless $self->has_subscribers("empty") 12 0 12
40 $self->on(
41 'error',
42 0 ▶ sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
43 0 say
44 sprintf("An error occured during crawling %s: %s", $_[2]->url, $_[1]);
45 }
46 12 ▶ ) unless $self->has_subscribers('error');
Branch: 1 branch
BranchTrueFalseTotal
unless $self->has_subscribers("error") 12 0 12
47 0 ▶ $self->on('res', sub { $_[1]->() }) unless $self->has_subscribers('res');
Subroutine __ANON__: not called CC=1 SCAR=0.2
Branch: 1 branch
BranchTrueFalseTotal
unless $self->has_subscribers("res") 10 2 12
48  
49 12 $self->ua->transactor->name($self->ua_name);
50 12 $self->ua->max_redirects(5);
51  
52 12 $self->{_loop_ids} = [];
53  
54 my $id = Mojo::IOLoop->recurring(
55 15 ▶ $self->clock_speed => sub {
Subroutine __ANON__: called CC=5 SCAR=16.5
56 15 my $queue = $self->queue;
57  
58 15 ▶ if (!$queue->length) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($queue->length) 2 13 15
59 2 ▶ $self->emit('empty') unless ($self->ua->active_conn);
Branch: 1 branch
BranchTrueFalseTotal
unless $self->ua->active_conn 2 0 2
60 2 return;
61 }
62 13 ▶ return if $self->ua->active_conn >= $self->max_conn;
Branch: 1 branch
BranchTrueFalseTotal
if $self->ua->active_conn >= $self->max_conn 0 13 13
63 return
64 13 ▶ if $self->ua->active_host($queue->next->url)
Branch: 1 branch
BranchTrueFalseTotal
if $self->ua->active_host($queue->next->url) >= $self->max_conn_per_host 0 13 13
65 >= $self->max_conn_per_host;
66 13 $self->process_job($queue->dequeue);
67 }
68 12 );
69  
70 12 push(@{$self->{_loop_ids}}, $id);
71  
72 12 ▶ if ($self->shuffle) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->shuffle) 0 12 12
73 my $id = Mojo::IOLoop->recurring(
74 0 ▶ $self->shuffle => sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
75 0 $self->queue->shuffle;
76 }
77 0 );
78  
79 0 push(@{$self->{_loop_ids}}, $id);
80 }
81 }
82  
83 13 ▶sub process_job {
Subroutine process_job: called CC=3 SCAR=11.4
Pod documented
84 13 my ($self, $job) = @_;
85  
86 13 ▶ my @args = ($job->method || 'get', $job->url);
Condition100%2/2
$job->method || 'get'
l!l
211
MC/DC100%1/1
$job->method || 'get'
$job->method
Truth table100%2/2
A
A= $job->method
Aresult
11
00
87 13 ▶ push(@args, form => $job->tx_params->to_hash) if $job->tx_params;
Branch: 1 branch
BranchTrueFalseTotal
if $job->tx_params 1 12 13
88 13 my $tx = $self->ua->build_tx(@args);
89  
90 13 $self->emit('req', $job, $tx->req);
91  
92 $self->ua->start(
93 13 ▶ $tx => sub {
Subroutine __ANON__: called CC=3 SCAR=13.1
94 13 my ($ua, $tx) = @_;
95  
96 13 $job->redirect(_urls_redirect($tx));
97  
98 13 my $res = $tx->res;
99  
100 13 ▶ unless ($res->code) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($res->code) 0 13 13
101 0 ▶ my $msg = $res->error ? $res->error->{message} : 'Unknown error';
Branch: 1 branch
BranchTrueFalseTotal
$res->error ? : 0 0 0
102 0 $self->emit('error', $msg, $job);
103 0 return;
104 }
105  
106 13 ▶ $self->emit('res', sub { $self->scrape($res, $job, $_[0]) }, $job, $res);
Subroutine __ANON__: called CC=1 SCAR=0.0
107  
108 13 $job->close;
109 }
110 13 );
111 }
112  
113 0 ▶sub say_start {
Subroutine say_start: not called CC=1 SCAR=6.9
Pod documented
114 0 my $self = shift;
115  
116 0 print <<"EOF";
117 ----------------------------------------
118 0 Crawling is starting with @{[ $self->queue->next->url ]}
119 0 Max Connection : @{[ $self->max_conn ]}
120 0 User Agent : @{[ $self->ua_name ]}
121 ----------------------------------------
122 EOF
123 }
124  
125 26 ▶sub scrape {
Subroutine scrape: called CC=10 SCAR=23.1
Pod documented
126 26 my ($self, $res, $job, $contexts) = @_;
127 26 my @ret;
128  
129 26 ▶ return unless $res->headers->content_length && $res->body;
Branch: 1 branch
BranchTrueFalseTotal
unless $res->headers->content_length and $res->body 1 25 26
Condition66%2/3
$res->headers->content_length and $res->body
!ll&&!rl&&r
1025
MC/DC50%1/2
$res->headers->content_length and $res->body
$res->headers->content_length $res->body
Truth table66%2/3
A and B
A= $res->headers->content_lengthB= $res->body
ABresult
0X0
100
111
130  
131 25 my $base = $job->url;
132 25 my $type = $res->headers->content_type;
133  
134 25 ▶ if ($type && $type =~ qr{^(text|application)/(html|xml|xhtml)}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($type and $type =~ qr"^(text|application)/(html|xml|xhtml)"u) 23 2 25
Condition66%2/3
$type and $type =~ qr"^(text|application)/(html|xml|xhtml)"u
!ll&&!rl&&r
0223
MC/DC50%1/2
$type and $type =~ qr"^(text|application)/(html|xml|xhtml)"u
$type $type =~ qr"^(text|application)/(html|xml|xhtml)"u
Truth table66%2/3
A and B
A= $typeB= $type =~ qr"^(text|application)/(html|xml|xhtml)"u
ABresult
0X0
100
111
135 23 ▶ if ((my $base_tag = $res->dom->at('base[href]'))) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $base_tag = $res->dom->at("base[href]")) 4 19 23
136 4 $base = resolve_href($base, $base_tag->attr('href'));
137 }
138 23 my $dom = Mojo::DOM->new(decoded_body($res));
139 23 my $handlers = reduce_html_handlers($self->html_handlers, $contexts);
140 23 for my $selector (sort keys %{$handlers}) {
141 $dom->find($selector)->each(
142 83 ▶ sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
143 83 my $dom = shift;
144 83 for ($handlers->{$selector}->($dom)) {
145 86 ▶ push(@ret, $self->_make_child($_, $dom, $job, $base)) if $_;
Branch: 1 branch
BranchTrueFalseTotal
if $_ 83 3 86
146 }
147 }
148 360 );
149 }
150 }
151  
152 25 ▶ if ($type && $type =~ qr{text/css}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($type and $type =~ qr"text/css"u) 1 24 25
Condition66%2/3
$type and $type =~ qr"text/css"u
!ll&&!rl&&r
0241
MC/DC50%1/2
$type and $type =~ qr"text/css"u
$type $type =~ qr"text/css"u
Truth table66%2/3
A and B
A= $typeB= $type =~ qr"text/css"u
ABresult
0X0
100
111
153 1 for (collect_urls_css(decoded_body($res))) {
154 1 push(@ret, $self->_make_child($_, $job->url, $job, $base));
155 }
156 }
157  
158 25 return @ret;
159 }
160  
161 2 ▶sub stop {
Subroutine stop: called CC=2 SCAR=6.9
Pod documented
162 2 my $self = shift;
163 2 ▶ while (my $id = shift @{$self->{_loop_ids}}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $id = shift @{$$self{"_loop_ids"};}) 2 2 4
164 2 Mojo::IOLoop->remove($id);
165 }
166 2 Mojo::IOLoop->stop;
167 }
168  
169 84 ▶sub _make_child {
Subroutine _make_child: called CC=9 SCAR=22.0
170 84 my ($self, $url, $context, $job, $base) = @_;
171  
172 84 ▶ return unless $url;
Branch: 1 branch
BranchTrueFalseTotal
unless $url 0 84 84
173 84 ▶ ($url, my $method, my $params) = @$url if (ref $url);
Branch: 1 branch
BranchTrueFalseTotal
if ref $url 6 78 84
174  
175 84 my $resolved = resolve_href($base, $url);
176  
177 84 ▶ return unless ($resolved->scheme =~ qr{^(http|https|ftp|ws|wss)$});
Branch: 1 branch
BranchTrueFalseTotal
unless $resolved->scheme =~ qr/^(http|https|ftp|ws|wss)$/u 11 73 84
178  
179 73 ▶ $resolved->query->append($params) if ($params && $method eq 'GET');
Branch: 1 branch
BranchTrueFalseTotal
if $params and $method eq "GET" 3 70 73
Condition100%3/3
$params and $method eq "GET"
!ll&&!rl&&r
6733
MC/DC100%2/2
$params and $method eq "GET"
$params $method eq "GET"
Truth table100%3/3
A and B
A= $paramsB= $method eq "GET"
ABresult
0X0
100
111
180  
181 73 my $child = $job->child(_url => $resolved, literal_uri => $url,
182 _context => $context);
183  
184 73 ▶ $child->method($method) if $method;
Branch: 1 branch
BranchTrueFalseTotal
if $method 6 67 73
185 73 ▶ $child->tx_params($params) if ($params && $method eq 'POST');
Branch: 1 branch
BranchTrueFalseTotal
if $params and $method eq "POST" 3 70 73
Condition100%3/3
$params and $method eq "POST"
!ll&&!rl&&r
6733
MC/DC100%2/2
$params and $method eq "POST"
$params $method eq "POST"
Truth table100%3/3
A and B
A= $paramsB= $method eq "POST"
ABresult
0X0
100
111
186  
187 73 return $child;
188 }
189  
190 59 ▶sub enqueue {
Subroutine enqueue: called CC=1 SCAR=0.0
Pod documented
191 59 my ($self, @jobs) = @_;
192 return
193 59 map { $self->queue->enqueue(WWW::Crawler::Mojo::Job->upgrade($_)) } @jobs;
194 }
195  
196 1 ▶sub requeue {
Subroutine requeue: called CC=1 SCAR=0.0
Pod documented
197 1 my ($self, @jobs) = @_;
198 return
199 1 map { $self->queue->requeue(WWW::Crawler::Mojo::Job->upgrade($_)) } @jobs;
200 }
201  
202 13 ▶sub _urls_redirect {
Subroutine _urls_redirect: called CC=2 SCAR=7.0
203 13 my $tx = shift;
204 13 my @urls;
205 13 ▶ @urls = _urls_redirect($tx->previous) if ($tx->previous);
Branch: 1 branch
BranchTrueFalseTotal
if $tx->previous 0 13 13
206 13 unshift(@urls, $tx->req->url->userinfo(undef));
207 13 return @urls;
208 }
209  
210 10 1;
211  
212 =head1 NAME
213  
214 WWW::Crawler::Mojo - A web crawling framework for Perl
215  
216 =head1 SYNOPSIS
217  
218 use strict;
219 use warnings;
220 use WWW::Crawler::Mojo;
221
222 my $bot = WWW::Crawler::Mojo->new;
223
224 $bot->on(res => sub {
225 my ($bot, $scrape, $job, $res) = @_;
226
227 $bot->enqueue($_) for $scrape->('#context');
228 });
229
230 $bot->enqueue('http://example.com/');
231 $bot->crawl;
232  
233 =head1 DESCRIPTION
234  
235 L<WWW::Crawler::Mojo> is a web crawling framework for those who are familiar with
236 L<Mojo>::* APIs.
237  
238 Althogh the module is only well tested for "focused crawl" at this point,
239 you can also use it for endless crawling by taking special care of memory usage.
240  
241 =head1 ATTRIBUTES
242  
243 L<WWW::Crawler::Mojo> inherits all attributes from L<Mojo::EventEmitter> and
244 implements the following new ones.
245  
246 =head2 clock_speed
247  
248 A number of main event loop interval in milliseconds. Defaults to 0.25.
249  
250 $bot->clock_speed(2);
251 my $clock = $bot->clock_speed; # 2
252  
253 =head2 html_handlers
254  
255 Sets HTML handlers of scrapper. Defaults to
256 WWW::Crawler::Mojo::ScraperUtil::html_handler_presets.
257  
258 $bot->html_handlers( {
259 'a[href]' => sub { return $_[0]->{href} },
260 'img[src]' => sub { return $_[0]->{src} },
261 } );
262  
263 =head2 max_conn
264  
265 An amount of max connections.
266  
267 $bot->max_conn(5);
268 say $bot->max_conn; # 5
269  
270 =head2 max_conn_per_host
271  
272 An amount of max connections per host.
273  
274 $bot->max_conn_per_host(5);
275 say $bot->max_conn_per_host; # 5
276  
277 =head2 queue
278  
279 L<WWW::Crawler::Mojo::Queue::Memory> object for default.
280  
281 $bot->queue(WWW::Crawler::Mojo::Queue::Memory->new);
282 $bot->queue->enqueue($job);
283  
284 =head2 shuffle
285  
286 An interval in seconds to shuffle the job queue. It also evalutated as boolean
287 for disabling/enabling the feature. Defaults to undef, meaning disable.
288  
289 $bot->shuffle(5);
290 say $bot->shuffle; # 5
291  
292 =head2 ua
293  
294 A L<WWW::Crawler::Mojo::UserAgent> instance.
295  
296 my $ua = $bot->ua;
297 $bot->ua(WWW::Crawler::Mojo::UserAgent->new);
298  
299 =head2 ua_name
300  
301 Name of crawler for User-Agent header.
302  
303 $bot->ua_name('my-bot/0.01 (+https://example.com/)');
304 say $bot->ua_name; # 'my-bot/0.01 (+https://example.com/)'
305  
306 =head1 EVENTS
307  
308 L<WWW::Crawler::Mojo> inherits all events from L<Mojo::EventEmitter> and
309 implements the following new ones.
310  
311 =head2 req
312  
313 Emitted right before crawler perform request to servers. The callback takes 3
314 arguments.
315  
316 $bot->on(req => sub {
317 my ($bot, $job, $req) = @_;
318  
319 # DO NOTHING
320 });
321  
322 =head2 res
323  
324 Emitted when crawler got response from server. The callback takes 4 arguments.
325  
326 $bot->on(res => sub {
327 my ($bot, $scrape, $job, $res) = @_;
328 if (...) {
329 $bot->enqueue($_) for $scrape->();
330 } else {
331 # DO NOTHING
332 }
333 });
334  
335 =head3 $bot
336  
337 L<WWW::Crawler::Mojo> instance.
338  
339 =head3 $scrape
340  
341 Scraper code reference for current document. The code takes optional argument
342 CSS selector for context and returns new jobs.
343  
344 for my $job ($scrape->($context)) {
345 $bot->enqueue($job)
346 }
347  
348 Optionally you can specify a scraping target container in CSS selector.
349  
350 @jobs = $scrape->('#container');
351 @jobs = $scrape->(['#container1', '#container2']);
352  
353 =head3 $job
354  
355 L<WWW::Crawler::Mojo::Job> instance.
356  
357 =head3 $res
358  
359 L<Mojo::Message::Response> instance.
360  
361 =head2 empty
362  
363 Emitted when queue length gets zero.
364  
365 $bot->on(empty => sub {
366 my ($bot) = @_;
367 say "Queue is drained out.";
368 });
369  
370 =head2 error
371  
372 Emitted when user agent returns no status code for request. Possibly caused by
373 network errors or un-responsible servers.
374  
375 $bot->on(error => sub {
376 my ($bot, $error, $job) = @_;
377 say "error: $error";
378 if (...) { # until failur occures 3 times
379 $bot->requeue($job);
380 }
381 });
382  
383 Note that server errors such as 404 or 500 cannot be catched with the event.
384 Consider res event for the use case instead of this.
385  
386 =head2 start
387  
388 Emitted right before crawl is started.
389  
390 $bot->on(start => sub {
391 my $self = shift;
392 ...
393 });
394  
395 =head1 METHODS
396  
397 L<WWW::Crawler::Mojo> inherits all methods from L<Mojo::EventEmitter> and
398 implements the following new ones.
399  
400 =head2 crawl
401  
402 Starts crawling loop.
403  
404 $bot->crawl;
405  
406 =head2 init
407  
408 Initializes crawler settings.
409  
410 $bot->init;
411  
412 =head2 process_job
413  
414 Processes a job.
415  
416 $bot->process_job;
417  
418 =head2 say_start
419  
420 Displays starting messages to STDOUT
421  
422 $bot->say_start;
423  
424 =head2 scrape
425  
426 Parses and discovers links in a web page and CSS. This performs scraping.
427 With the optional 4th argument, you can specify a CSS selector to container
428 you would collect URLs within.
429  
430 $bot->scrape($res, $job, );
431 $bot->scrape($res, $job, $selector);
432 $bot->scrape($res, $job, [$selector1, $selector2]);
433  
434 =head2 stop
435  
436 Stop crawling.
437  
438 $bot->stop;
439  
440 =head2 enqueue
441  
442 Appends one or more URLs or L<WWW::Crawler::Mojo::Job> objects. Returns the jobs
443 actually added.
444  
445 my @jobs = $bot->enqueue('http://example.com/index1.html');
446  
447 OR
448  
449 my @jobs = $bot->enqueue($job1, $job2);
450  
451 OR
452  
453 my @jobs = $bot->enqueue(
454 'http://example.com/index1.html',
455 'http://example.com/index2.html',
456 'http://example.com/index3.html',
457 );
458  
459 =head2 requeue
460  
461 Appends one or more URLs or jobs for re-try. This accepts same arguments as
462 enqueue method. Returns the jobs actually added.
463  
464 $self->on(error => sub {
465 my ($self, $msg, $job) = @_;
466 if (...) { # until failur occures 3 times
467 $bot->requeue($job);
468 }
469 });
470  
471 =head1 EXAMPLE
472  
473 L<https://github.com/jamadam/WWW-Flatten>
474  
475 =head1 AUTHOR
476  
477 Keita Sugama, E<lt>sugama@jamadam.comE<gt>
478  
479 =head1 COPYRIGHT AND LICENSE
480  
481 Copyright (C) jamadam
482  
483 This program is free software; you can redistribute it and/or
484 modify it under the same terms as Perl itself.
485  
486 =cut
« blib/lib/WWW/Crawler/Mojo/Queue/MySQL.pm ↑ Summary lib/WWW/Crawler/Mojo/Job.pm »