PDAScraper.pm

filter: Statementstmt 26.6% 40 / 150 Branchbran 0.0% 0 / 56 Conditioncond 0.0% 0 / 16 MC/DCmcdc 0.0% 0 / 9 Subroutinesub 80.0% 12 / 15 Podpod 0.0% 0 / 4 totaltotal 20.8% 52 / 250 CC 40 SCAR 67.9
CC
40
Cov
18%
scrape
1332.0
proxy
6.0
download_location
6.0
CRAP 888.9
↑ Summary PDAScraper/ABC.pm »
1 package WWW::PDAScraper;
2 1 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
3 1 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 1 ▶use Data::Dumper;
Subroutine BEGIN: called CC=1 SCAR=0.0
5  
6 1 ▶BEGIN {
Subroutine BEGIN: called CC=1 SCAR=0.0
7 1 ▶ use Exporter;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 1 ▶ use vars qw($VERSION @ISA @EXPORT);
Subroutine BEGIN: called CC=1 SCAR=0.0
9 1 $VERSION = 0.1;
10 1 @ISA = qw( Exporter );
11 1 @EXPORT = qw( &scrape );
12 1 ▶ use URI::URL;
Subroutine BEGIN: called CC=1 SCAR=0.0
13 1 ▶ use HTML::TreeBuilder;
Subroutine BEGIN: called CC=1 SCAR=0.0
14 1 ▶ use HTML::Template;
Subroutine BEGIN: called CC=1 SCAR=0.0
15 1 ▶ use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
16 1 ▶ use LWP::UserAgent;
Subroutine BEGIN: called CC=1 SCAR=0.0
17 }
18  
19 1 my $ua = LWP::UserAgent->new();
20  
21 1 my $download_location = "$ENV{'HOME'}/scrape";
22  
23 0 ▶sub proxy {
Subroutine proxy: not called CC=2 SCAR=17.9
Pod undocumented
24 0 ▶ if ( ref( $_[0] ) eq 'WWW::PDAScraper' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $_[0] eq 'WWW::PDAScraper') { } 0 0 0
25 0 my ( $self, $proxy ) = @_;
26 0 $ua->proxy( ['http'], $proxy );
27 } else {
28 0 my $proxy = shift();
29 0 $ua->proxy( ['http'], $proxy );
30 }
31 }
32  
33 0 ▶sub download_location {
Subroutine download_location: not called CC=2 SCAR=17.9
Pod undocumented
34 0 ▶ if ( ref( $_[0] ) eq 'WWW::PDAScraper' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $_[0] eq 'WWW::PDAScraper') { } 0 0 0
35 0 my ( $self, $location ) = @_;
36 0 $download_location = $location;
37 } else {
38 0 my $location = shift();
39 0 $download_location = $location;
40 }
41 }
42  
43 1 ▶sub new {
Subroutine new: called CC=3 SCAR=14.2
Pod undocumented
44 1 my $pkg = shift;
45 0 my @submodules = map { "WWW::PDAScraper::$_" } @_;
46 1 for ( @submodules ) {
47 0 ▶ eval "require $_" || croak( "$@" );
Branch: 1 branch
BranchTrueFalseTotal
eval "require $_" or croak("$@") 0 0 0
48 }
49 1 bless { submodules => \@submodules }, $pkg;
50 }
51  
52 0 ▶sub scrape {
Subroutine scrape: not called CC=36 SCAR=71.9
Pod undocumented
53 0 my $self = {};
54 0 ▶ if ( ref( $_[0] ) eq 'WWW::PDAScraper' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $_[0] eq 'WWW::PDAScraper') { } 0 0 0
55 0 $self = shift;
56 } else {
57 0 my @submodules = map { "WWW::PDAScraper::$_" } @_;
58 0 for ( @submodules ) {
59 0 ▶ eval "require $_" || croak( "$_ - $@" );
Branch: 1 branch
BranchTrueFalseTotal
eval "require $_" or croak("$_ - $@") 0 0 0
60 }
61 0 $self->{'submodules'} = \@submodules;
62 }
63 0 for ( @{ $self->{'submodules'} } ) {
64 0 my $obj = $_->config();
65 0 my $template = undef;
66 0 my @all_links = ();
67 0 my @good_links = ();
68 0 my $tree = undef;
69 0 my $chunk = undef;
70 0 my $file_number = 0;
71 0 my $response = $ua->get( $obj->{'start_from'} );
72 ### get the front page which has the links
73 0 ▶ unless ( $response->is_success() ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($response->is_success) 0 0 0
74 0 carp(
75 "$obj->{name} error: failed to get starter page: $obj->{'start_from'}"
76 );
77 0 next;
78 }
79 0 my $page = $response->content();
80  
81 0 ▶ if ( $obj->{'chunk_spec'} ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($obj->{'chunk_spec'}) { } 0 0 0
elsif ($obj->{'chunk_regex'}) { } 0 0 0
82 ### if we're parsing the HTML the Good Way using TreeBuilder
83 0 ▶ unless ( $chunk =
Branch: 1 branch
BranchTrueFalseTotal
unless ($chunk = "HTML::TreeBuilder"->new_from_content($page)) 0 0 0
84 HTML::TreeBuilder->new_from_content( $page ) )
85 {
86 0 carp( "$obj->{name} - $@" );
87 0 next;
88 }
89  
90 0 ▶ unless ( $chunk->elementify() ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($chunk->elementify) 0 0 0
91 0 carp( "$obj->{name} - $@" );
92 0 next;
93 }
94  
95 $chunk =
96 0 $chunk->look_down( @{ $obj->{'chunk_spec'} } );
97
98 0 ▶ unless ( defined($chunk) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $chunk) 0 0 0
99 0 carp( "$obj->{name} error: \n"
100 . "nothing on the page matches the 'chunk_spec'\n"
101 . "which tells $_ where to find the links.\n");
102 0 next;
103 }
104  
105  
106 } elsif ( $obj->{'chunk_regex'} )
107 { # not the case with the new scientist
108 ### if we're parsing the HTML the Bad Way using a regex
109  
110 0 $page =~ $obj->{'chunk_regex'};
111 0 ▶ unless ( defined $1 ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $1) 0 0 0
112 0 carp(
113 "$obj->{name} Regex failed to match on $obj->{'start_from'}"
114 );
115 0 return;
116 }
117 0 $chunk = HTML::TreeBuilder->new_from_content( $1 );
118 0 $chunk->elementify();
119  
120 } else {
121 ### if we're just grabbing the whole page, probably not a good
122 ### idea, but see link_spec below for a way of filtering links
123 0 $chunk =
124 HTML::TreeBuilder->new_from_content( $page );
125 0 ▶ unless ( $chunk->elementify() ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($chunk->elementify) 0 0 0
126 0 carp( "$obj->{name} - $@" );
127 0 next;
128 }
129 }
130  
131 0 ▶ if ( defined( $obj->{'link_spec'} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $obj->{'link_spec'}) { } 0 0 0
132 ### If we've got a TreeBuilder link filter to grab only
133 ### the links which match a certain format
134 @all_links =
135 $chunk->look_down( '_tag', 'a',
136 0 @{ $obj->{'link_spec'} } );
137 } else {
138  
139 0 @all_links = $chunk->look_down( '_tag', 'a' );
140 }
141 0 for ( @all_links ) {
142 ### Avoid three problem conditions -- no text means
143 ### we've probably got image links (often duplicates)
144 ### -- "#" as the href means a JavaScript link --
145 ### a tags with no HREF are also no use to us:
146 next
147 0 ▶ unless ( defined( $_->attr( 'href' ) )
Branch: 1 branch
BranchTrueFalseTotal
unless defined $_->attr("href") and $_->as_text ne "" and $_->attr("href") ne "#" 0 0 0
Condition0%0/6
defined $_->attr("href") and $_->as_text ne "" and $_->attr("href") ne "#"
!ll&&!rl&&r
000
defined $_->attr("href") and $_->as_text ne ""
!ll&&!rl&&r
000
MC/DC0%0/3
defined $_->attr("href") and $_->as_text ne "" and $_->attr("href") ne "#"
defined $_->attr("href") $_->as_text ne "" $_->attr("href") ne "#"
Truth table0%0/4
A and B and C
A= defined $_->attr("href")B= $_->as_text ne ""C= $_->attr("href") ne "#"
ABCresult
0XX0
10X0
1100
1111
148 && $_->as_text() ne ''
149 && $_->attr( 'href' ) ne '#' );
150 0 my $href = $_->attr( 'href' );
151 ### It's expected that we'll need to transform
152 ### the URL from regular to print-friendly:
153 0 my $regex_success = 0;
154 0 ▶ if ( defined( $obj->{'url_regex'} )
Branch: 2 branches
BranchTrueFalseTotal
if (defined $obj->{'url_regex'} and ref $obj->{'url_regex'}[1] eq 'CODE') { } 0 0 0
elsif (defined $obj->{'url_regex'}) { } 0 0 0
Condition0%0/3
defined $obj->{"url_regex"} and ref $obj->{"url_regex"}[1] eq "CODE"
!ll&&!rl&&r
000
MC/DC0%0/2
defined $obj->{"url_regex"} and ref $obj->{"url_regex"}[1] eq "CODE"
defined $obj->{"url_regex"} ref $obj->{"url_regex"}[1] eq "CODE"
Truth table0%0/3
A and B
A= defined $obj->{"url_regex"}B= ref $obj->{"url_regex"}[1] eq "CODE"
ABresult
0X0
100
111
155 && ref( $obj->{'url_regex'}->[1] ) eq 'CODE' )
156 {
157 ### PerlMonk Roy Johnson is my saviour here.
158 ### Solution to the problem of some url regexes
159 ### needing backreferences and some not.
160 0 ▶ if (
Branch: 1 branch
BranchTrueFalseTotal
if ($href =~ s/$obj->{"url_regex"}[0]/${$obj->{"url_regex"}[1]->();};/e) 0 0 0
161 $href =~ s{$obj->{'url_regex'}->[0]}
162 0 {${$obj->{'url_regex'}->[1]->()}}e
163 )
164 {
165 0 $regex_success = 1;
166 }
167 } elsif ( defined( $obj->{'url_regex'} ) ) {
168 ### If there is a regex object at all:
169 0 ▶ if (
Branch: 1 branch
BranchTrueFalseTotal
if ($href =~ s/$obj->{"url_regex"}[0]/$obj->{"url_regex"}[1]/) 0 0 0
170 $href =~ s{$obj->{'url_regex'}->[0]}
171 {$obj->{'url_regex'}->[1]}
172 )
173 {
174 0 $regex_success = 1;
175 }
176 }
177 0 ▶ if ( $regex_success == 0 && $obj->{'url_regex'} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($regex_success == 0 and $obj->{"url_regex"}) 0 0 0
Condition0%0/3
$regex_success == 0 and $obj->{"url_regex"}
!ll&&!rl&&r
000
MC/DC0%0/2
$regex_success == 0 and $obj->{"url_regex"}
$regex_success == 0 $obj->{"url_regex"}
Truth table0%0/3
A and B
A= $regex_success == 0B= $obj->{"url_regex"}
ABresult
0X0
100
111
178 0 carp(
179 "$obj->{name} - URL RegEx failed to transform URL: $href"
180 );
181 }
182 ### Transform the URL from relative to absolute:
183 my $url =
184 0 URI::URL->new( $href, $obj->{'start_from'} );
185 0 my $abs_url = $url->abs();
186 ### Make a data structure with all the stuff we're
187 ### going to get on the next pass:
188 0 push(
189 @good_links,
190 {
191 text => $_->as_text(),
192 url => "$abs_url"
193 }
194 );
195 }
196 0 ▶ if ( scalar( @good_links ) == 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @good_links == 0) 0 0 0
197 0 carp( "$obj->{name} No 'good' links found." );
198 0 return;
199 }
200 0 ( my $foldername = $obj->{'name'} ) =~ s/\W//g;
201 ### Make a foldername with no non-word chars
202  
203 0 ▶ unless ( -e $download_location ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (-e $download_location) 0 0 0
204 ### Make a scrape folder if there isn't one
205 0 ▶ mkdir $download_location
Condition0%0/2
$download_location || croak(" __LINE__ making scrape folder $@")
l!l
00
MC/DC0%0/1
$download_location || croak(" __LINE__ making scrape folder $@")
$download_location
Truth table0%0/2
A
A= $download_location
Aresult
11
00
206 || croak( " __LINE__ making scrape folder $@" );
207 }
208 0 ▶ unless ( -e "$download_location/$foldername" ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (-e "$download_location/$foldername") 0 0 0
209 ### Make a folder for this content if there isn't one
210 0 ▶ mkdir "$download_location/$foldername"
Condition0%0/2
"$download_location/$foldername" || croak(" __LINE__ making $foldername folder $@")
l!l
00
MC/DC0%0/1
"$download_location/$foldername" || croak(" __LINE__ making $foldername folder $@")
"$download_location/$foldername"
Truth table0%0/2
A
A= "$download_location/$foldername"
Aresult
11
00
211 || croak(
212 " __LINE__ making $foldername folder $@" );
213 }
214 0 foreach ( @good_links ) {
215 0 my $response = $ua->get( $_->{'url'} );
216 0 ▶ unless ( $response->is_success() ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($response->is_success) 0 0 0
217 0 warn "didn't get " . $_->{'url'} . "$!" . $/;
218 0 $_ = undef;
219 0 next;
220 }
221 0 my $page = $response->content();
222 ### TO DO: arbitrary number of further regexes
223 ### in case users want to clean content up more?
224 ### Filenames sprintf'd for neatness only:
225 0 my $local_file =
226 sprintf( "%03d.html", $file_number );
227 ### add a localfile value to the AoH for use in the index:
228 0 $_->{localfile} = $local_file;
229 ### Print out the actual content page locally:
230 0 ▶ open( PAGE,
Branch: 1 branch
BranchTrueFalseTotal
open PAGE, ">$download_location/$foldername/$local_file" or croak(" __LINE__ $download_location/$foldername/$local_file $@") 0 0 0
231 ">$download_location/$foldername/$local_file" )
232 || croak(
233 " __LINE__ $download_location/$foldername/$local_file $@"
234 );
235 0 print PAGE $page;
236 0 close( PAGE );
237 0 $file_number++;
238 }
239  
240 0 @good_links = grep { defined( $_ ) } @good_links;
241  
242 # in case we had to undef a bad link in foreach ( @good_links )
243  
244 ### [die_on_bad_params is off because the AoH contains
245 ### one item we don't need, the original URL]
246 0 my $template_code = '<html>
247 <head>
248 <tmpl_if name="encoding">
249 <meta http-equiv="content-type" content="text/html; charset=<tmpl_var name=encoding>">
250 <tmpl_else>
251 <meta http-equiv="content-type" content="text/html; charset=utf-8">
252 </tmpl_if>
253 <title><tmpl_var name="sitename"></title>
254 </head>
255 <body>
256 <h1><tmpl_var name="sitename"></h1>
257 <ul><tmpl_loop name="links">
258 <li>
259 <a href="<tmpl_var name="localfile">"><tmpl_var name="text"></a>
260 </li>
261 </tmpl_loop></ul>
262 </body>
263 </html>';
264 0 $template = HTML::Template->new(
265 scalarref => \$template_code,
266 debug => 0,
267 die_on_bad_params => 0
268 );
269 ### Use the name and the links array to fill out the template:
270 0 ▶ if ( exists( $obj->{'encoding'} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $obj->{"encoding"}) 0 0 0
271 0 $template->param( encoding => $obj->{'encoding'} );
272 }
273  
274 $template->param(
275 links => \@good_links,
276 0 sitename => $obj->{'name'}
277 );
278 ### Output the index page locally:
279 0 ▶ open( INDEX,
Branch: 1 branch
BranchTrueFalseTotal
open INDEX, ">$download_location/$foldername/index.html" or croak("$@") 0 0 0
280 ">$download_location/$foldername/index.html" )
281 || croak( "$@" );
282 0 ▶ unless ( print INDEX $template->output() ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (print INDEX $template->output) 0 0 0
283 0 carp( "Error in HTML::Template output" );
284 0 return;
285 }
286 0 close( INDEX );
287 ### Clean up after HTML::Tree as recommended
288 0 $chunk->delete();
289 }
290 }
291 1 1;
292  
293 =head1 Name
294  
295 WWW::PDAScraper - Class for scraping PDA-friendly content from websites
296  
297 =head1 Synopsis
298  
299 use WWW::PDAScraper;
300 my $scraper = WWW::PDAScraper->new qw ( NewScientist Yahoo::Entertainment );
301 $scraper->scrape();
302
303 or
304
305 use WWW::PDAScraper;
306 my $scraper = WWW::PDAScraper->new;
307 $scraper->scrape qw( NewScientist Yahoo::Entertainment );
308  
309 or
310
311 perl -MWWW::PDAScraper -e "scrape qw( NewScientist Yahoo::Entertainment )"
312  
313  
314 =head1 Description
315  
316 Having written various kludgey scripts to download
317 PDA-friendly content from various websites, I
318 decided to try and write a generalised solution
319 which would
320  
321 * parse out the section of a news page which contains
322 the links we want
323
324 * munge those links into the URL for the print-friendly
325 version, if possible
326  
327 * download those pages and make an index page for them
328  
329 The moving of the pages to your PDA is not part of the
330 scope of the module: the open-source browser and
331 "distiller", Plucker, from B<http://plkr.org/>
332 is recommended. Just get it to read the index.html
333 file with a depth of 1 from disk, using a URL like
334 file:///path/to/index.html
335  
336 =head1 The Sub-modules
337  
338 WWW::PDAScraper uses a set of rules for scraping a
339 particular website from a second module, i.e.
340 C<WWW::PDAScraper::Yahoo::Entertainment::TV> contains the rules for
341 scraping the Yahoo TV News website:
342  
343 package WWW::PDAScraper::Yahoo::Entertainment::TV;
344 # WWW::PDAScraper.pm rules for scraping the
345 # Yahoo TV website
346 sub config {
347 return {
348 name => 'Yahoo TV',
349 start_from => 'http://news.yahoo.com/i/763',
350 chunk_spec => [ "_tag", "div", "id", "indexstories" ],
351 url_regex => [ '$', '&printer=1' ]
352 };
353 }
354 1;
355  
356 A more or less random selection of modules is included, as well as a
357 full set for Yahoo, to demonstrate a logical set of modules in categories.
358  
359 Creating a new sub-module ought to be relatively simple, see the
360 template provided, WWW::PDAScraper::Template.pm - you need C<name>,
361 C<start_from>, then either C<chunk_spec> or C<url_spec>, then
362 optionally a C<url_regex> for transformation into the print-friendly URL.
363  
364 Then either move your new module to the same location as the other ones
365 on your system, or make sure they're available to your script with a line
366 like C<use lib '/path/to/local/modules/PDAScraper/'>
367  
368 =head1 USAGE
369  
370 WWW::PDAScraper ought to be very simple to run, assuming you have
371 the right sub-module(s).
372  
373 It only has two main methods, new() and scrape(), and two supplementary
374 ones, for assigning a proxy server to the user-agent and one for
375 over-riding the default download location.
376  
377 Either object-oriented, loading the sub-module(s) as part of "new":
378  
379 use WWW::PDAScraper;
380 my $scraper = WWW::PDAScraper->new qw ( NewScientist Yahoo::Entertainment );
381 $scraper->scrape();
382  
383 or object-oriented, loading the sub-module(s) as part of each
384 call to scrape():
385  
386 use WWW::PDAScraper;
387 my $scraper = WWW::PDAScraper->new;
388 $scraper->scrape qw( NewScientist Yahoo::Entertainment );
389 $scraper->scrape qw( SomethingElse );
390  
391 or procedural:
392  
393 use WWW::PDAScraper;
394 scrape qw( NewScientist Yahoo::Entertainment );
395  
396 or from the command line:
397  
398 perl -MWWW::PDAScraper -e "scrape qw( NewScientist Yahoo::Entertainment )"
399
400 The only extras involved would be adding a proxy to the user-agent
401 and/or over-riding the default download location of $ENV{'HOME'}/scrape/
402  
403 Object-oriented:
404
405 use WWW::PDAScraper;
406 my $scraper = WWW::PDAScraper->new;
407 $scraper->proxy('http://your.proxy.server:port/');
408 $scraper->download_location("/path/to/folder/");
409  
410 procedural:
411  
412 use WWW::PDAScraper;
413 proxy('http://your.proxy.server:port/');
414 download_location("/path/to/folder/");
415  
416 =head1 I wish I didn't need this code
417  
418 In the days of modern web publishing, I shouldn't
419 need to create this code. All websites should make
420 themselves PDA-friendly by the use of client detection
421 or smart CSS or XML. But they don't.
422  
423 =head1 Bugs
424  
425 The websites will certainly change, and at that time
426 the sub-modules will stop working. There's no way around that.
427  
428 Obviously it would be useful if there were a developer/user
429 community which contributed new modules and updated the old ones.
430  
431 =head1 See Also
432  
433 HTML::Element, for the syntax of C<chunk_spec> in sub-modules.
434  
435 =head1 To do
436  
437 The user-agent should really be part of the object, I guess.
438 That would be neater.
439  
440 And it should actually use WWW::Robot instead of LWP so it
441 doesn't hammer servers.
442  
443 And we could either add arbitrary numbers of
444 regexes for fixing up the pages of sites which
445 don't have a print-friendly version of the page,
446 or add a second level of parsing to find the
447 print-friendly link, for sites which don't have a
448 logical relationship between the regular link and
449 the print-friendly.
450  
451 =head1 Author
452  
453 John Horner
454 CPAN ID: CODYP
455
456 bounce@johnhorner.nu
457 http://pdascraper.johnhorner.nu/
458  
459 =head1 Copyright
460  
461 This program is free software; you can redistribute
462 it and/or modify it under the same terms as Perl itself.
463  
464  
465 =cut
466  
467 ############################################# main pod documentation end ##
468  
↑ Summary PDAScraper/ABC.pm »