blib/lib/WWW/Crawler/Mojo/ScraperUtil.pm untested

filter: Statementstmt 0.0% 0 / 135 Branchbran 0.0% 0 / 54 Conditioncond 0.0% 0 / 35 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 16 Podpod 0.0% 0 / 10 totaltotal 0.0% 0 / 250 CC 28 SCAR 48.5
CC
28
Cov
0%
html_handler_presets
306.0
guess_encoding
30.0
reduce_html_handlers
20.0
CRAP 128.2
1 package WWW::Crawler::Mojo::ScraperUtil;
2 use strict;
3 use warnings;
4 use Mojo::Base -base;
5 use Encode qw(find_encoding);
6 use Exporter 'import';
7  
8 our @EXPORT_OK = qw(collect_urls_css html_handler_presets reduce_html_handlers
9 guess_encoding encoder decoded_body resolve_href);
10  
11 my $charset_re = qr{\bcharset\s*=\s*['"]?([a-zA-Z0-9_\-]+)['"]?}i;
12  
13 sub collect_urls_css {
14 map { s/^(['"])// && s/$1$//; $_ } (shift || '') =~ m{url\((.+?)\)}ig;
15 }
16  
17 sub decoded_body {
18 my $res = shift;
19 return encoder(guess_encoding($res))->decode($res->body);
20 }
21  
22 sub encoder {
23 for (shift || 'utf-8', 'utf-8') {
24 if (my $enc = find_encoding($_)) {
25 return $enc;
26 }
27 }
28 }
29  
30 sub guess_encoding {
31 my $res = shift;
32 my $type = $res->headers->content_type;
33 return unless ($type);
34 my $charset = ($type =~ $charset_re)[0];
35 return $charset if ($charset);
36 return _guess_encoding_html($res->body) if ($type =~ qr{text/(html|xml)});
37 return _guess_encoding_css($res->body) if ($type =~ qr{text/css});
38 }
39  
40 sub html_handler_presets {
41 return {
42 'script[src]' => sub { $_[0]->{src} },
43 'link[href]' => sub { $_[0]->{href} },
44 'a[href]' => sub { $_[0]->{href} },
45 'img[src]' => sub { $_[0]->{src} },
46 'area' => sub { $_[0]->{href}, $_[0]->{ping} },
47 'embed[src]' => sub { $_[0]->{src} },
48 'frame[src]' => sub { $_[0]->{src} },
49 'iframe[src]' => sub { $_[0]->{src} },
50 'input[src]' => sub { $_[0]->{src} },
51 'object[data]' => sub { $_[0]->{data} },
52 'form' => sub {
53 my $dom = shift;
54 my (%seed, $submit);
55  
56 $dom->find("[name],[type='submit'],[type='image']")->each(
57 sub {
58 my $e = shift;
59 $seed{my $name = $e->{name}} ||= [] if $e->{name};
60  
61 if ($e->tag eq 'select' && $name) {
62 my $found = 0;
63 if (exists $e->{multiple}) {
64 $e->find('option[selected]')->each(
65 sub {
66 push(@{$seed{$name}}, shift->{value});
67 $found++;
68 }
69 );
70 }
71 elsif (my $opts = $e->at('option[selected]')) {
72 push(@{$seed{$name}}, $opts->{value});
73 $found++;
74 }
75 if (!$found) {
76 $e->find('option:nth-child(1)')->each(
77 sub {
78 push(@{$seed{$name}}, shift->{value});
79 }
80 );
81 }
82 }
83 elsif ($e->tag eq 'textarea') {
84 push(@{$seed{$name}}, $e->text);
85 }
86  
87 return unless (my $type = $e->{type});
88  
89 if (!$submit && grep { $_ eq $type } qw{submit image}) {
90 $submit = 1;
91 push(@{$seed{$name}}, $e->{value}) if $name;
92 }
93 if ($name) {
94 if (grep { $_ eq $type } qw{text hidden number password date}) {
95 push(@{$seed{$name}}, $e->{value});
96 }
97 elsif (grep { $_ eq $type } qw{checkbox}) {
98 push(@{$seed{$name}}, $e->{value}) if (exists $e->{checked});
99 }
100 elsif (grep { $_ eq $type } qw{radio}) {
101 push(@{$seed{$name}}, $e->{value}) if (exists $e->{checked});
102 }
103 }
104 }
105 );
106  
107 return [
108 $dom->{action} || '',
109 uc($dom->{method} || 'GET'),
110 Mojo::Parameters->new(%seed)
111 ];
112 },
113 'meta[content]' => sub {
114 return $1
115 if ($_[0] =~ qr{http\-equiv="?Refresh"?}i
116 && (($_[0]->{content} || '') =~ qr{URL=(.+)}i)[0]);
117 return;
118 },
119 'style' => sub {
120 collect_urls_css(shift->content);
121 },
122 '[style]' => sub {
123 collect_urls_css(shift->{style});
124 },
125 'urlset[xmlns^=http://www.sitemaps.org/schemas/sitemap/]' => sub {
126 @{$_->find('url loc')->map(sub { $_->content })->to_array};
127 }
128 };
129 }
130  
131 sub reduce_html_handlers {
132 my $handlers = $_[0];
133 my $contexts = ref $_[1] ? $_[1] : [$_[1]];
134 my $ret;
135 for my $sel (keys %$handlers) {
136 my $cb = $handlers->{$sel};
137 for my $cont (@$contexts) {
138 $ret->{($cont ? $cont . ' ' : '') . $sel} = sub {
139 return if ($_[0]->xml && _wrong_dom_detection($_[0]));
140 return $cb->($_[0]);
141 }
142 }
143 }
144 return $ret;
145 }
146  
147 sub resolve_href {
148 my ($base, $href) = @_;
149 $href =~ s{^\s|\s$|\n}{}g;
150 $href = ref $href ? $href : Mojo::URL->new($href);
151 $base = ref $base ? $base : Mojo::URL->new($base);
152 my $abs = $href->fragment(undef)->to_abs($base);
153 my $path_parts = $abs->path->parts;
154 shift @{$path_parts} while (@$path_parts && $path_parts->[0] eq '..');
155 return $abs;
156 }
157  
158 sub _guess_encoding_css {
159 return (shift =~ qr{^\s*\@charset ['"](.+?)['"];}is)[0];
160 }
161  
162 sub _guess_encoding_html {
163 my $head = (shift =~ qr{<head>(.+)</head>}is)[0] or return;
164 my $charset;
165 Mojo::DOM->new($head)->find('meta[http\-equiv=Content-Type]')->each(
166 sub {
167 $charset = (shift->{content} =~ $charset_re)[0];
168 }
169 );
170 return $charset;
171 }
172  
173 sub _wrong_dom_detection {
174 my $dom = shift;
175 while ($dom = $dom->parent) {
176 return 1 if ($dom->tag && $dom->tag eq 'script');
177 }
178 return;
179 }
180  
181 use 5.010;
182  
183 1;
184  
185 =head1 NAME
186  
187 WWW::Crawler::Mojo::ScraperUtil - Scraper utitlities
188  
189 =head1 SYNOPSIS
190  
191 =head1 DESCRIPTION
192  
193 This class inherits L<Mojo::UserAgent> and override start method for storing
194 user info
195  
196 =head1 ATTRIBUTES
197  
198 WWW::Crawler::Mojo::ScraperUtil implements following attributes.
199  
200 =head1 METHODS
201  
202 WWW::Crawler::Mojo::ScraperUtil implements following methods.
203  
204 =head2 collect_urls_css
205  
206 Collects URLs out of CSS.
207  
208 @urls = collect_urls_css($dom);
209  
210 =head2 decoded_body
211  
212 Returns decoded response body for given L<Mojo::Message::Request> using
213 guess_encoding and encoder.
214  
215 =head2 encoder
216  
217 Generates L<Encode> instance for given name. Defaults to L<Encode::utf8>.
218  
219 =head2 html_handler_presets
220  
221 Returns common html handler in hash reference.
222  
223 my $handlers = html_handlers();
224  
225 =head2 reduce_html_handlers
226  
227 Narrows html handler selectors by prefixing container CSS snippets.
228  
229 my $handlers = html_handlers($handlers, ['#header', '#footer li']);
230
231 $handlers->{img} = sub {
232 my $dom = shift;
233 return $dom->{src};
234 };
235
236 my @urls;
237 for my $selector (sort keys %{$handlers}) {
238 $dom->find($selector)->each(sub {
239 push(@urls, $handlers->{$selector}->(shift));
240 })->to_array;
241 }
242  
243 =head2 resolve_href
244  
245 Resolves URLs with a base URL.
246  
247 WWW::Crawler::Mojo::resolve_href($base, $uri);
248  
249 =head2 guess_encoding
250  
251 Guesses encoding of HTML or CSS with given L<Mojo::Message::Response> instance.
252  
253 $encode = WWW::Crawler::Mojo::guess_encoding($res) || 'utf-8'
254  
255 =head1 AUTHOR
256  
257 Keita Sugama, E<lt>sugama@jamadam.comE<gt>
258  
259 =head1 COPYRIGHT AND LICENSE
260  
261 Copyright (C) Keita Sugama.
262  
263 This program is free software; you can redistribute it and/or
264 modify it under the same terms as Perl itself.
265  
266 =cut