WWW/Scraper.pm

filter: Statementstmt 46.4% 13 / 28 Branchbran 0.0% 0 / 4 Conditioncond n/a MC/DCmcdc n/a Subroutinesub 71.4% 5 / 7 Podpod n/a totaltotal 46.1% 18 / 39 CC 5 SCAR 26.6
CC
5
Cov
41%
import
30.0
__ANON__
2.0
BEGIN
1.3
CRAP 14.3
« WWW/Scraper/ScraperDiscovery.pm ↑ Summary WWW/Scraper/Opcode/TR.pm »
1
2 ####################################################################################
3 ####################################################################################
4 ####################################################################################
5 ####################################################################################
6 package WWW::Scraper;
7
8 1 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 require Exporter;
10 1 ▶use vars qw($VERSION $MAINTAINER @ISA @EXPORT @EXPORT_OK $PRINT_VERSION);
Subroutine BEGIN: called CC=1 SCAR=0.0
11
12 $VERSION = '3.05';
13
14 my $CVS_VERSION = sprintf("%d.%02d", q$Revision: 1.2 $ =~ /(\d+)\.(\d+)/);
15 $MAINTAINER = 'Glenn Wood http://search.cpan.org/search?mode=author&query=GLENNWOOD';
16 $PRINT_VERSION = 0;
17
18 sub import
19 0 ▶{
Subroutine import: not called CC=5 SCAR=34.0
20 0 my $package = shift;
21
22 0 for my $opts (grep { "HASH" eq ref($_) } @_)
23 {
24 0 for my $opt ( keys %$opts ) {
25 my $optfunc =
26 {
27 0 ▶ 'PRINT_VERSION' => sub { $WWW::Scraper::PRINT_VERSION = 1; }
Subroutine __ANON__: not called CC=1 SCAR=6.9
28 0 }->{$opt};
29 0 ▶ if ( $optfunc ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($optfunc) { } 0 0 0
30 0 &$optfunc($opts->{$opt});
31 } else {
32 0 warn "Unknown option '$opt' in $package\n";
33 }
34 }
35 }
36
37 # Prints "WWW::Scraper v3.01", as appropriate to the sub-class of Scraper.
38 0 ▶ eval "print \"$package v\$$package\::VERSION\\\n\"" if ( $WWW::Scraper::PRINT_VERSION );
Branch: 1 branch
BranchTrueFalseTotal
if $WWW::Scraper::PRINT_VERSION 0 0 0
39
40 0 @_ = ($package, grep { "HASH" ne ref($_) } @_);
41 0 goto &Exporter::import;
42 }
43
44
45 1 ▶use Carp ();
Subroutine BEGIN: called CC=1 SCAR=0.0
46 1 ▶use URI::URL; # some Unix boxes simply won't load this one via WWW:Search, so . . .
Subroutine BEGIN: called CC=1 SCAR=0.0
47
48 0 ▶use WWW::Search( 2.28 );
Subroutine BEGIN: called CC=1 SCAR=2.6
49 use WWW::Scraper::Request;
50 use WWW::Scraper::Response;
51 use WWW::Scraper::Response::generic;
52 use WWW::Scraper::TidyXML;
53 use WWW::Scraper::Opcode;
54
55 @EXPORT_OK = qw( generic_option testParameters trimTags trimLFs trimLFLFs trimComments
56 @ENGINES_WORKING addURL trimXPathAttr trimXPathHref
57 findNextForm findNextFormInXML removeScriptsInHTML cleanupHeadBody);
58
59
60 #------------------------------------------------------------------#
61 # Here we begin our gradual migration from "can-o-worms" to
62 # Class::Struct structured Scraper.
63 { package WWW::Scraper::_struct_;
64 use Class::Struct;
65 struct ( 'WWW::Scraper::_struct_' =>
66 {
67 'response' => '$'
68 ,'searchEngineHome' => '$'
69 ,'searchEngineLogo' => '$'
70 ,'errorMessage' => '$'
71 ,'_artifactFolder' => '$' # Folder into which certain Scraper artifacts will be gathered.
72 ,'_responseClass' => '$'
73 ,'_wantsNativeRequest' => '$'
74 ,'_wwwSearchBackend' => '$'
75 ,'_forInterator' => '$'
76 ,'_retryGetCount' => '$'
77 ,'_tidyXmlObject' => '$'
78 ,'pageNumber' => '$' # Page number of the current 'response' object.
79 ,'_scraperRequest' => '$'
80 ,'_scraperFrame' => '$'
81 ,'_scraperDetail' => '$'
82 }
83 );
84 }
85 use base qw( WWW::Scraper::_struct_ WWW::Search Exporter );
86 my @HitStack = ();
87 #------------------------------------------------------------------#
88
89 sub new {
90 my ($class, $subclass, $native_query, $native_options) = @_;
91
92 my ($self, $wantsNativeRequest);
93 $subclass = '' unless $subclass;
94 $wantsNativeRequest = $subclass =~ s/^NativeRequest\:\:(.*)$/$1/;
95 if ( $subclass =~ m-^\.\.[\/](.*)$- ) { # Allow the form "../name" to indicate
96 die "The '..\\backend' form is deprecated in favor of scraperFrame = 'WWW::Search::backend' - see HeadHunter.pm for an example.\n";
97 } else {
98 if ( $subclass =~ s/^(.*)\((.*)\)$/$1/ ) {
99 my $subclassVersion = $2;
100 eval "use WWW::Scraper::$subclass($subclassVersion)";
101 if ( $@ ) {
102 print "Can't use engine $subclass($subclassVersion): $@\n";
103 return undef;
104 }
105 }
106
107 ## > > > > > > #############################################################################################
108 #############################################################################################
109 #############################################################################################
110 #############################################################################################
111 # THIS STUFF IS A FACTORING OF WWW::Search::new() - we must track any of Martin's changes!
112 # $self = new WWW::Search("../Scraper::$subclass");
113 my $newclass = "${class}::$subclass";
114 if (!defined(&$newclass))
115 {
116 eval "use $newclass";
117 Carp::croak("unknown Scraper interface '$newclass': $@") if ($@);
118 }
119
120 $self = bless {
121 engine => $newclass,
122 maximum_to_retrieve => 500, # both pages and hits
123 interrequest_delay => 0.25, # in seconds
124 agent_name => "WWW::Scraper/$VERSION",
125 agent_e_mail => 'glenwood@alumni.caltech.edu;MartinThurn@iname.com',
126 env_proxy => 0,
127 http_method => 'GET',
128 http_proxy => '',
129 http_proxy_user => undef,
130 http_proxy_pwd => undef,
131 timeout => 60,
132 _debug => 0,
133 _parse_debug => 0,
134 search_from_file => undef,
135 search_to_file => undef,
136 search_to_file_index => 0,
137 @_,
138 # variable initialization goes here
139 }, $newclass;
140 $self->reset_search();
141 }
142 #############################################################################################
143 #############################################################################################
144
145 $self->_wantsNativeRequest($wantsNativeRequest);
146
147 $self->{'agent_name'} = 'Mozilla/4.0 (compatible; MSIE 4.01; Windows 95)';#"Mozilla/WWW::Scraper/$VERSION";
148 $self->{'scraperQF'} = 0; # Explicitly declare 'scraperQF' as the deprecated mode.
149 $self->{'scraperName'} = $subclass;
150
151 $self->_init(); # Some property initializations, mostly to eliminate useless diagnostic warnings.
152
153 # Finally, call the sub-scraper's init() method.
154 return $self->init($subclass, $native_query, $native_options);
155 }
156
157 sub _init {
158 my $self = shift;
159 $self->{cache} = []; # Eliminate some useless "warnings" from WWW::Search(lines 544-549) during make test, and elsewhere.
160 $self->pageNumber(0); # Use of uninitialized value in addition (+) at lib/WWW/Search/Scraper.pm line 609
161
162 if ( $self->scraperFrame ) {
163 my @scfld = @{$self->scraperFrame};
164 my $next_scaffold = $scfld[$#scfld] if ref($scfld[$#scfld]) eq 'ARRAY';
165 WWW::Scraper::Opcode::InitiateScaffold($next_scaffold) if $next_scaffold; #$self->GetScraperFrame)};
166 }
167
168 if ( $self->scraperDetail ) {
169 my @scfld = @{$self->scraperDetail};
170 my $next_scaffold = $scfld[$#scfld] if ref($scfld[$#scfld]) eq 'ARRAY';
171 WWW::Scraper::Opcode::InitiateScaffold($next_scaffold) if $next_scaffold; #$self->GetScraperDetail);
172 }
173 }
174
175
176 # The Scraper module should override this.
177 sub init {
178 my ($self, $subclass, $native_query, $native_options) = @_;
179 my $scraperFrame = $self->scraperFrame();
180 if ( ${$scraperFrame}[0] =~ m{^WWW::Search::(.*)$} ) {
181 $self->_wwwSearchBackend(new WWW::Search($1, $native_query, $native_options)); # Uses a WWW::Search backend.
182 } else {
183 if ( ref($native_query) && !$native_options ) {
184 $native_options = $native_query;
185 $native_query = undef;
186 }
187 $self->native_query($native_query, $native_options);
188 }
189 return $self;
190 }
191
192
193 # To help avoid embarrassment when he inadvertently releases test, debug or tracing code to CPAN, Glenn uses this.
194 sub isGlennWood { return $ENV{'VSROOT'} and ($ENV{'USERNAME'} eq 'Glenn') and ($ENV{'USERDOMAIN'} eq 'ORCHID'); }
195
196 # Access methods for the structural declarations of this Scraper engine.
197 use vars qw($scraperRequest $scraperFrame $scraperDetail);
198 sub SetScraperRequest { my ($self,$rqst) = @_; $self->_scraperRequest($rqst); }
199 sub SetScraperFrame { my ($self,$frame) = @_; $self->_scraperFrame($frame);
200 WWW::Scraper::Opcode::InitiateScaffold($frame->[1]) if $frame; #$self->GetScraperFrame)};
201 }
202 sub SetScraperDetail { my ($self,$frame) = @_; $self->_scraperDetail($frame);
203 WWW::Scraper::Opcode::InitiateScaffold($frame->[1]) if $frame; #$self->GetScraperFrame)};
204 }
205 sub GetScraperRequest { $_[0]->_scraperRequest; }
206 sub GetScraperFrame { $_[0]->_scraperFrame; }
207 sub GetScraperDetail { $_[0]->_scraperDetail; }
208
209 sub scraperFrameX {
210 $_[0]->{'_options'}{'scrapeFrame'} = $_[1] if $_[1];
211 return $_[0]->{'_options'}{'scrapeFrame'}
212 }
213
214 # backward compatible, pre v3.01 ( gdw.2003.03.14 )
215 sub scraperRequest { return $_[0]->GetScraperRequest }
216 sub scraperFrame { $_[0]->SetScraperFrame($_[1]) if $_[1]; return $_[0]->GetScraperFrame }
217 sub scraperDetail { $_[0]->SetScraperDetail($_[1]) if $_[1]; return $_[0]->GetScraperDetail }
218
219 # Return empty testFrame for sub-scrapers that choose not to provide one.
220 sub testParameters {
221 my ($self) = @_;
222
223 if ( ref $self ) {
224 $self->{'isTesting'} = 1;
225 }
226
227 my $isNotTestable = WWW::Scraper::isGlennWood()?0:'No testParameters provided.';
228 return {
229 'SKIP' => $isNotTestable
230 ,'testNativeQuery' => 'search scraper'
231 ,'expectedOnePage' => 9
232 ,'expectedMultiPage' => 11
233 ,'expectedBogusPage' => 0
234 };
235 }
236
237 sub artifactFolder {
238 my ($self, $fldr) = @_;
239 if ( $fldr ) {
240 mkdir $fldr unless -d $fldr;
241 $self->_artifactFolder($fldr);
242 }
243 return $self->_artifactFolder();
244 }
245
246
247 sub generic_option
248 {
249 my ($option) = @_;
250 return 1 if $option =~ /^scrape/;
251 return WWW::Search::generic_option($option);
252 }
253
254 # A generalize get/set method for object attributes.
255 sub _attr {
256 my ($self, $attr, $value) = @_;
257 my $rtn = $self->{$attr};
258 $self->{$attr} = $value if defined $value;
259 # neat idea, but we've got to rewrite a lot of method invocations to make this ok. gdw.2001.07.04
260 # if ( wantarray ) {
261 # return $rtn if 'ARRAY' eq ref $rtn;
262 # return [$rtn];
263 # }
264 return $rtn;
265 }
266 # ## # ## # ## # ## # ## # ## # ## # ## # ## # ## # ## # ## # ## # ## # ## # ## # ##
267 ### # ## # ## # ## # ## # ## # ## # ## # ## # ## # ## # ## # ## # ## # ## # ## # ##
268 ## # ## # ## # ## # ## # ## # ## # ## # ## # ## # ## # ## # ## # ## # ## # ## # ## #
269 sub query { $_[0]->_attr('_query', $_[1]) }
270 sub queryDefaults { $_[0]->_attr('_queryDefaults', $_[1]) }
271 sub queryOptions { $_[0]->_attr('_queryOptions', $_[1]) }
272 sub fieldTranslations { $_[0]->_attr('_fieldTranslations', $_[1]) }
273
274
275 # Some tracing options -
276 # U - lists URLs as they are generated/accessed.
277 # T - lists progress of each TidyXML tree-walking operation.
278 # d - excruciating details about parsing the results and details pages.
279 sub ScraperTrace {
280 return undef unless defined $_[0]->{'_traceFlags'};
281 return $_[0]->{'_traceFlags'} unless $_[1]; # default traceFlags if no match string sent.
282 return ( $_[0]->{'_traceFlags'} =~ m-$_[1]- );
283 }
284 sub setScraperTrace {
285 $_[0]->{'_traceFlags'} = $_[1];
286 }
287
288 # ## # ## # ## # ## # ## # ## # ## # ## # ## # ## # ## # ## # ## # ## # ## # ## # ##
289 ### # ## # ## # ## # ## # ## # ## # ## # ## # ## # ## # ## # ## # ## # ## # ## # ##
290 ## # ## # ## # ## # ## # ## # ## # ## # ## # ## # ## # ## # ## # ## # ## # ## # ## #
291 sub SetRequest {
292 my ($self, $rqst) = @_;
293
294 my $nonBlankWWWSearchNativeQuery = 'nonBlankWWWSearchNativeQuery';
295 if ( $rqst ) {
296 # Make sure the request object is ready for us.
297 $rqst->prepare($self);
298
299 # Move the debug option from the request to the Scraper module.
300 $self->{'_debug'} = $rqst->_Scraper_debug() if defined $rqst->_Scraper_debug();
301
302 $self->{'_scraperRequest'} = $rqst;
303
304 $nonBlankWWWSearchNativeQuery = $rqst->_native_query() || $nonBlankWWWSearchNativeQuery;
305 }
306
307 # WWW::Search(2.26) required native_query to be non-blank, even before it hands it off to Scraper!
308 $self->{'native_query'} = $nonBlankWWWSearchNativeQuery unless $self->{'native_query'};
309
310 return $self->{'_scraperRequest'};
311 }
312
313 sub GetRequest { return $_[0]->{'_scraperRequest'} }
314
315 sub SetResponseClass { $_[0]->_responseClass($_[1]) }
316 sub GetResponseClass { $_[0]->_responseClass() }
317
318
319 sub native_setup_search
320 {
321 my $self = shift;
322 my ($native_query, $native_options) = @_;
323 $native_query = WWW::Search::unescape_query($native_query); # Thanks, but no thanks, Search.pm!
324
325 $self->{'_first_url'} = undef;
326 $self->{'_first_url_method'} = undef;
327
328 my $scraperRequest = $self->scraperRequest;
329
330 # ## # ## # ## # ## # ## # ## # ## # ## # ## # ## # ## # ## # ## # ## # ## # ## # ##
331 #
332 # This pecular set of code translates old interface mode into 'canonical request' mode,
333 #
334 # NOTE THAT IF THE CANONICAL REQUEST HAS BEEN SET, ALL native_setup_search() PARAMETERS ARE IGNORED!
335 #
336 # otherwise, they get picked up here.
337
338 # ## # ## # ## # ## # ## # ## # ## # ## # ## # ## # ## # ## # ## # ## # ## # ## # ##
339 # Get the scraperRequest declaration of the Scraper module, or fake one (as in when using a WWW::Search module).
340 unless ( $scraperRequest ) {
341 $scraperRequest =
342 {
343 'type' => 'SEARCH' # This is a WWW::Search module - notify native_setup_search_NULL() of that.
344 # This is the basic URL on which to build the query.
345 ,'url' => 'http://'
346 # names the native input field to recieve the query string.
347 ,'nativeQuery' => 'query'
348 # specify defaults, by native field names
349 ,'nativeDefaults' => { }
350 ,'fieldTranslations' => undef # This gives us a null %inputsHash, so WWW::Scraper will ignore that functionality (hopefully)
351 , 'cookies' => 0 # The WWW::Search module must maintain its own cookies.
352 };
353 $self->scraperRequest($scraperRequest, $native_query, $native_options);
354 }
355 # ## # ## # ## # ## # ## # ## # ## # ## # ## # ## # ## # ## # ## # ## # ## # ## # ##
356
357 #$self->SetRequest( new WWW::Scraper::Request($self, $native_query, $native_options) ) unless ( $self->GetRequest());
358
359 # These traceFlags will ultimately come from many places . . .
360 #$self->setScraperTrace($self->{'_debug'}) unless $self->{'_traceFlags'};
361
362 for ( $self->scraperRequest()->{'type'} ) {
363 m/^SHERLOCK$/ && do { return $self->native_setup_search_SHERLOCK(@_); };
364 m/^FORM$/ && do { return $self->native_setup_search_FORM(@_); };
365 m/^QUERY$|^GET$/ && do { return $self->native_setup_search_QUERY(@_); };
366 m/^POST$/ && do { $self->{'_http_method'} = 'POST';
367 return $self->native_setup_search_QUERY(@_); };
368 m/^SEARCH$/ && do { return $self->native_setup_search_NULL(@_); };
369 m/^WSDL$/ && do { return $self->native_setup_search_WSDL(@_); };
370 m/^WWW::Search/ && do { return $self->native_setup_search_WWW_Search(@_); };
371 die "Invalid mode in WWW::Scraper - '$_'\n";
372 }
373 }
374
375
376
377 sub native_setup_search_SHERLOCK
378 {
379 my ($self, $native_query, $native_options) = @_;
380 $self->SetRequest( new WWW::Scraper::Request($self, $native_query, $native_options) ) unless ( $self->GetRequest());
381 die "Unimplemented mode in WWW::Scraper - 'SHERLOCK'\n";
382 }
383
384
385 sub native_setup_search_FORM
386 {
387 my ($self, $native_query, $native_options) = @_;
388 $self->SetRequest( new WWW::Scraper::Request($self, $native_query, $native_options) ) unless ( $self->GetRequest());
389
390 $self->user_agent('user');
391 $self->{_next_to_retrieve} = 0;
392
393 # $scraperForm = [ 'url', 'formIndex' (or formName, NYI), 'submitButtonName' or undef ]
394 my $url = $self->scraperRequest($native_query, $native_options)->{'url'};
395 if ( ref $url ) {
396 $self->{'_base_url'} = &$url($self, $self->GetRequest()->_native_query(), $self->{'native_options'});
397 } else {
398 $self->{'_base_url'} = $url;
399 }
400 unless ( $self->{'_base_url'} ) {
401 print STDERR "No base url was specified by ".ref($self).".pm, so no search is possible.\n";
402 undef $self->{'_next_url'};
403 return undef;
404 }
405 $self->{'_http_method'} = 'GET' unless $self->{'_http_method'};
406
407 print STDERR 'FORM URL: '.$self->{'_base_url'} . "\n" if ($self->ScraperTrace('U'));
408 my $response = $self->http_request($self->{'_http_method'}, $self->{'_base_url'});
409 unless ( $response->is_success ) {
410 print STDERR "Request for FORM failed in Scraper.pm: ".$response->message() if $self->ScraperTrace();
411 return undef ;
412 }
413
414 my @forms = HTML::Form->parse($response->content(), $response->base());
415 return undef unless @forms;
416 my $formNameOrNumber = $self->scraperRequest->{'formNameOrNumber'};
417 my $form;
418 if ( $formNameOrNumber =~ m{^\d+$} ) { # is formNameOrNumber a number?
419 $form = $forms[$self->scraperRequest->{'formNameOrNumber'} or 0];
420 } else { # it is a name, not a number.
421 # Unfortunately, HTML::Form->parse() does not stash the forms' names, so we use
422 # this inperfect method to get to them (inperfect? what if "<form" is in a comment?)
423 my (@formNames) = ($response->content =~ m{<form\s[^>]*name=['"]?([^'" >]+)['"> ]}gsi);
424 for my $tmp (@forms) {
425 if ( $formNameOrNumber eq shift @formNames ) {
426 $form = $tmp;
427 last;
428 }
429 }
430 }
431 return undef unless $form;
432
433 $self->{'_http_method'} = $self->{'search_method'} = uc $form->method() || 'POST';
434
435 # Finally figure out the url.
436 # Process the inputs.
437 # Fill in the defaults, first
438 my %optsHash = %{$self->queryDefaults()};
439 # Override those with what came with the request.
440 my $options_ref = $self->{'native_options'};
441 foreach (sort keys %$options_ref) {
442 $optsHash{$_} = $$options_ref{$_};
443 };
444 $optsHash{$self->scraperRequest()->{'nativeQuery'}} = $self->GetRequest()->_native_query() if $self->scraperRequest()->{'nativeQuery'};
445
446 for my $key (sort keys %optsHash) {
447 my $opts = $optsHash{$key};
448 # if ( 'ARRAY' eq ref $opts ) {
449 # for ( @$opts) {
450 # $options .= "$key=".cgi_escape($_)."&";
451 # }
452 # } else {
453 my $field = $form->find_input($key);
454 next unless $field;
455 my $fldtyp = $field->type();
456 if ( $fldtyp eq 'option' ) {
457 my $n = 1;
458 SUBFIELD: while ( my $field = $form->find_input($key, undef, $n++) ) {
459 for ( @{$field->{'menu'}} ) {
460 if ( $_ eq $opts ) {
461 $field->value($opts);
462 last SUBFIELD;
463 }
464 }
465 }
466 #'password'', ``hidden'', ``textarea'', ``image'', ``submit'', ``radio'',
467 #``checkbox'', ``option''...my $x = $field->form_name_value();
468 }
469 else {
470 $field->value($opts);
471 }
472 }
473 #bless( {
474 # 'seen' => [
475 # 1,
476 # 0
477 # ],
478 # 'menu' => [
479 # undef,
480 # '2'
481 # ],
482 # 'multiple' => 'multiple',
483 # 'current' => 0,
484 # 'size' => '4',
485 # 'type' => 'option',
486 # 'name' => 'countyIDs'
487 # }, 'HTML::Form::ListInput' )
488
489 my $submit_button = $form->find_input($self->scraperRequest()->{'submitButton'}, 'submit');
490 $submit_button = $form->find_input($self->scraperRequest()->{'submitButton'}, 'image') unless $submit_button;
491 die "Can't find 'submit' button named '".$self->scraperRequest()->{'submitButton'}."' in '$url'" unless $submit_button;
492 my $req = $submit_button->click($form); #
493
494 $self->{_base_url} = $self->{_next_url} = $req->uri();
495 $self->{_base_url} .= '?'.$req->content() if $req->content();
496 print STDERR "FORM SUBMIT: ".$self->{_base_url} . "\n" if $self->ScraperTrace('U');
497 }
498
499
500 sub native_setup_search_QUERY
501 {
502 my ($self, $native_query, $native_options) = @_;
503 $self->SetRequest( new WWW::Scraper::Request($self, $native_query, $native_options) ) unless ( $self->GetRequest());
504
505 $self->user_agent('user');
506 $self->{_next_to_retrieve} = 0;
507
508 my $url = $self->scraperRequest($native_query, $native_options)->{'url'};
509
510 if ( ref $url ) {
511 $self->{'_base_url'} = &$url($self, $self->GetRequest()->_native_query(), $self->{'native_options'});
512 } else {
513 $self->{'_base_url'} = $url;
514 }
515 unless ( $self->{'_base_url'} ) {
516 print STDERR "No base url was specified by ".ref($self).".pm, so no search is possible.\n";
517 undef $self->{'_next_url'};
518 return undef;
519 }
520 $self->{'_http_method'} = 'GET' unless $self->{'_http_method'};
521 # $rqst->{'_base_url'} = $self->{'_base_url'};
522
523 $self->{'_next_url'} = $self->generateQuery();
524 print STDERR $self->{_next_url} . "\n" if $self->ScraperTrace('U');
525 }
526
527
528 # This one handles the deprecated Scraper::native_setup_search()
529 sub native_setup_search_NULL
530 {
531 my ($self, $native_query, $native_options) = @_;
532 $self->SetRequest( new WWW::Scraper::Request($self, $native_query, $native_options) ) unless ( $self->GetRequest());
533
534 die "native_setup_search_NULL() is no longer supported!";
535 # This is a cheap way to get back to the non-canonical form.
536 # We'll clean up the rest of this code later, so it won't look
537 # like such a waste of time to prepare(canonical) just to come
538 # back to the legacy form here. gdw.2001.06.30
539 #my ($native_query, $native_options) = ($self->GetRequest()->_native_query(), $self->{'native_options'});
540
541 my $subJob = 'Perl';
542 $self->user_agent('user');
543 $self->{_next_to_retrieve} = 0;
544 if (!defined($self->{_options})) {
545 $self->{_options} = {
546 # 'search_url' => 'http://www.defaultdomain.com/plus-cgi-bin/and-cgi-program-name' SHOULD BE PASSED IN AS AN OPTION.
547 };
548 };
549 $self->{'_http_method'} = 'GET'; # SHOULD BE PASSED IN AS AN OPTION; this is the default.
550
551 my($options_ref) = $self->{_options};
552 if (defined($native_options)) {
553 # Copy in new options.
554 foreach (keys %$native_options) {
555 $options_ref->{$_} = $native_options->{$_};
556 };
557 };
558 # Process the options.
559 # (Now in sorted order for consistency regarless of hash ordering.)
560 my($options) = '';
561 foreach (sort keys %$options_ref) {
562 # printf STDERR "option: $_ is " . $options_ref->{$_} . "\n";
563 next if (generic_option($_));
564 $options .= $_ . '=' . $options_ref->{$_} . '&';
565 };
566 $self->{_debug} |= $options_ref->{'search_debug'};
567 $self->{_debug} = 2 if ($options_ref->{'search_parse_debug'});
568 $self->{_debug} = 0 if (!defined($self->{_debug}));
569
570 # Finally figure out the url.
571 $self->{_base_url} =
572 $self->{_next_url} =
573 $self->{_options}{'search_url'} .
574 "?" . $options .
575 "KEYWORDS=" . $native_query;
576
577 print STDERR $self->{_next_url} . "\n" if $self->ScraperTrace('U');
578 }
579
580
581 sub native_setup_search_WSDL
582 {
583 my ($self, $native_query, $native_options) = @_;
584
585 $self->user_agent('user');
586 $self->{_next_to_retrieve} = 0;
587
588 my $url = $self->scraperRequest(@_)->{'url'};
589
590 if ( ref $url ) {
591 $self->{'_base_url'} = &$url($self, $self->GetRequest()->_native_query(), $self->{'native_options'});
592 } else {
593 $self->{'_base_url'} = $url;
594 }
595 unless ( $self->{'_base_url'} ) {
596 print STDERR "No base url was specified by ".ref($self).".pm, so no search is possible.\n";
597 undef $self->{'_next_url'};
598 return undef;
599 }
600 $self->{'_http_method'} = 'GET' unless $self->{'_http_method'};
601 # $rqst->{'_base_url'} = $self->{'_base_url'};
602
603 $self->{'_next_url'} = $self->generateQuery();
604
605 print STDERR $self->{_next_url} . "\n" if $self->ScraperTrace('U');
606 }
607
608
609
610 ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ###
611 ### Use WWW::Search "backend", attached to this Scraper canonical engine, to do the scraping.
612 sub native_setup_search_WWW_Search {
613 my ($self, $native_query, $native_options) = shift;
614 $self->SetRequest( new WWW::Scraper::Request($self, $native_query, $native_options) ) unless ( $self->GetRequest());
615 my $oSearch = $self->_wwwSearchBackend();
616 ($oSearch->{'native_query'}, $oSearch->{'native_options'}) = ($self->GetRequest()->_native_query(), $self->{'native_options'});
617 return $oSearch->native_setup_search($oSearch->{'native_query'}, $oSearch->{'native_options'});
618 }
619
620 sub cgi_escape
621 {
622 my $text = join(' ', @_);
623 $text = '' unless defined $text;
624 $text =~ s/([^ A-Za-z0-9])/$URI::Escape::escapes{$1}/g; #"
625 $text =~ s/ /+/g;
626 return $text;
627 }
628
629 ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ###
630 # The options have been prepared into the Scraper Request object by Scraper::Request::prepare().
631 # generateQuery() creates the HTTP query based on _scraperNativeQuery.
632 sub generateQuery {
633 my ($self) = @_;
634
635 # Process the inputs.
636 my $options = ''; # Was scraperRequest, now fieldTranslations
637
638 # The following line allows us to use native_query(), ala pre-v2.00 modules, with this Scraper.pm
639 # $options = $self->queryFieldName().'='.$rqst->_native_query().'&' if $rqst->_native_query() and $self->queryFieldName();
640
641 my $vals = $self->GetRequest->_scraperNativeQuery();
642
643 # Fill in the defaults from the Scraper module.
644 my $defaults = $self->queryDefaults();
645 map { $vals->{$_} = $defaults->{$_} unless defined $vals->{$_} } keys %$defaults;
646
647 for my $key (sort keys %{$vals}) {
648 my $opts = $vals->{$key};
649 if ( 'ARRAY' eq ref $opts ) {
650 for ( @$opts) {
651 $options .= "$key=".cgi_escape($_)."&";
652 }
653 } else {
654 $options .= "$key=".cgi_escape($opts)."&";
655 }
656 };
657 chop $options;
658 return $self->{'_base_url'}.$options;
659 }
660
661
662
663 ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ###
664 sub native_retrieve_some
665 {
666 my $self = shift;
667 if ( $self->_wwwSearchBackend() ) {
668 return $self->_wwwSearchBackend()->native_retrieve_some(@_);
669 }
670 my $debug = $self->{_debug};
671
672 $self->{'total_hits_count'} = 0; # for HIT(i)
673
674 # fast exit if already done
675 AGAIN:
676 unless ( $self->{_next_url} ) {
677 print STDERR "END_OF_SEARCH: _next_url is empty.\n" if $self->ScraperTrace('U');
678 return undef;
679 };
680
681 # get some
682 print STDERR ref($self)."::native_retrieve_some: fetching " . $self->{_next_url} . "\n" if ($self->ScraperTrace('U') && $debug );
683
684 my $method = $self->{'_http_method'};
685 $method = 'POST' unless $method;
686
687 print STDERR "Fetching NEXT_URL via $method: '".$self->{_next_url}."'\n" if $self->ScraperTrace('U');
688
689 $self->{'_last_url'} = $self->{_next_url};
690 unless ( $self->{'_first_url'} ) {
691 $self->{'_first_url'} = $self->{_next_url};
692 $self->{'_first_url_method'} = $method;
693 }
694
695 # Some search engines don't connect every time, so we might give them a couple of retries.
696 my $response;
697 $self->_retryGetCount('0');
698 while ( $self->keepRetrying() ) {
699 $response = $self->http_request($method, $self->{_next_url});
700
701 while ( $response->code() eq '302' ) {
702 my $redirect = $response->header('location');
703 if ( $redirect =~ m-^/- ) {
704 my $url = $self->{_next_url};
705 $url =~ m-^(\w+://[^/]*)/-;
706 $url = $1;
707 $self->{_next_url} = $url.$redirect;
708 } elsif ( ! ($redirect =~ m-^(\w+://[^/]*)-) ) {
709 my $url = $self->{_next_url};
710 $url =~ m-^(.*/)-;
711 $url = $1;
712 $self->{_next_url} = $url.$redirect;
713 } else {
714 $self->{_next_url} = $redirect;
715 }
716 print STDERR "Redirected to: '".$self->{_next_url}."'\n" if $self->ScraperTrace('U');
717 $method = $self->scraperRequest()->{'redirectMethod'} || $method;
718 $response = $self->http_request($method, $self->{_next_url});
719 }
720
721 $self->{'_last_url'} = $self->{'_next_url'}; $self->{'_next_url'} = undef;
722 $self->response($response);
723
724 if ( $response->is_success ) {
725 $self->pageNumber($self->pageNumber()+1);
726 last;
727 }
728 else {
729 $self->errorMessage("Request failed in Scraper.pm: ".$response->message());
730 print STDERR $self->errorMessage()."\n" if $self->ScraperTrace();
731 print STDERR $response->content()."\n" if $self->ScraperTrace('f'); # detailed failure reports.
732 return undef;
733 }
734 }
735
736 my $hits_found = $self->scrape($response->content(), $self->{_debug});
737
738 # sleep so as to not overload the remote engine
739 $self->user_agent_delay if ( defined($self->{_next_url}) );
740
741 return $hits_found;
742 }
743
744
745 # Some search engines don't connect every time, so we might give them a couple of retries.
746 sub keepRetrying {
747 my $self = shift;
748 $self->_retryGetCount($self->_retryGetCount()+1);
749 my $retryCount = $self->scraperRequest()->{'retry'} || 1;
750 if ( $self->_retryGetCount() > $retryCount ) {
751 return 0;
752 }
753 return 1;
754 }
755
756
757 ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ###
758 # Given a candidate hit, do post-selection.
759 # Return 1 to keep this hit, 0 to cast it away.
760 sub postSelect {
761 my ($self, $rqst, $rslt) = @_;
762 # By default, the Request object will do the postSelect for the Scraper module.
763 # If the Scraper module wants to override that, then it overrides this Scraper::postSelect().
764
765 my $fields = $rqst->FieldTitles;
766
767 my $fieldTranslationsTable = $self->fieldTranslations();
768 my $fieldTranslations = $fieldTranslationsTable->{'*'}; # We'll do this until context sensitive work is done - gdw.2001.08.18
769 my $fieldTranslation;
770
771 for ( keys %$fields ) {
772 $fieldTranslation = $$fieldTranslations{$_};
773 next if defined $fieldTranslation and $fieldTranslation eq '';
774 # 'fieldTranslation' may be a string naming the option, or
775 # a subroutine tranforming the field into a (nam,val) pair,
776 # or a FieldTranslation object - that's the only one that'll have a postSelect() method!
777 if ( 'CODE' eq ref $fieldTranslation ) {
778 }
779 elsif ( ref $fieldTranslation ) # We assume any other ref is an object of some sort.
780 {
781 return 0 unless $fieldTranslation->postSelect($self, $rqst, $rslt);
782 }
783 }
784 return $rqst->postSelect($self, $rslt);
785 }
786
787
788 { package WWW::Search;
789 sub scraperName {
790 return $_[0]->{'scraperName'};
791 }
792
793 }
794
795
796
797 {
798 package LWP::RobotUA;
799
800 # Dice always redirects the first query page via 302 status code.
801 # BAJobs frequently (but not always) redirects via 302 status code.
802 # We need to tell LWP::RobotUA that it's ok to redirect on Dice and BAJobs.
803 sub redirect_ok
804 {
805 # draft-ietf-http-v10-spec-02.ps from www.ics.uci.edu, specify:
806 #
807 # If the 30[12] status code is received in response to a request using
808 # the POST method, the user agent must not automatically redirect the
809 # request unless it can be confirmed by the user, since this might change
810 # the conditions under which the request was issued.
811
812 my($self, $request) = @_;
813 return 1 if $request->uri() =~ m-seeker\.dice\.com/jobsearch/jobsearch_r\.epl-i;
814 return 1 if $request->uri() =~ m-seeker\.dice\.com/jobsearch/resultSummary\.epl-i;
815 # return 1 if $request->uri() =~ m-jobsearch\.dice\.com/jobsearch/jobsearch\.cgi-i;
816 return 1 if $request->uri() =~ m-www\.bajobs\.com/jobseeker/searchresults\.jsp-i;
817 return 1 if $request->uri() =~ m-\.techies\.com/Common-i;
818 return 0 if $request->method eq "POST";
819 1;
820 }
821 }
822
823
824 ##################### < E X C E P T I O N S > ######################
825 # some kind of problem with URI in LWP since LWP(5.60)
826 eval <<EOT
827 use URI::http;
828 { package URI::http;
829 sub abs {
830 my \$self = shift;
831 return \$self->SUPER::abs(\@_) if \$_[0];
832 return \$self->canonical(\@_);
833 }
834 use URI::https;
835 { package URI::https;
836 sub abs {
837 my \$self = shift;
838 return \$self->SUPER::abs(\@_) if \$_[0];
839 return \$self->canonical(\@_);
840 }
841 EOT
842 if ( ($LWP::VERSION ge '5.60') );
843 #################### < / E X C E P T I O N S > #####################
844
845
846 ##### ##### ##### ##### ##### ##### ##### ##### ##### ##### ##### ##### ##### ##### ##### #####
847 ##### ##### ##### ##### ##### ##### ##### ##### ##### ##### ##### ##### ##### ##### ##### #####
848 ##### ##### ##### ##### ##### ##### ##### ##### ##### ##### ##### ##### ##### ##### ##### #####
849 ##### ##### ##### ##### ##### ##### ##### ##### ##### ##### ##### ##### ##### ##### ##### #####
850 ##### ##### ##### ##### ##### ##### ##### ##### ##### ##### ##### ##### ##### ##### ##### #####
851 ##### ##### ##### ##### ##### ##### ##### ##### ##### ##### ##### ##### ##### ##### ##### #####
852 ##### ##### ##### ##### ##### ##### ##### ##### ##### ##### ##### ##### ##### ##### ##### #####
853 ##### ##### ##### ##### ##### ##### ##### ##### ##### ##### ##### ##### ##### ##### ##### #####
854 ##### ##### ##### ##### ##### ##### ##### ##### ##### ##### ##### ##### ##### ##### ##### #####
855 ##### ##### ##### ##### ##### ##### ##### ##### ##### ##### ##### ##### ##### ##### ##### #####
856 ##### ##### ##### ##### ##### ##### ##### ##### ##### ##### ##### ##### ##### ##### ##### #####
857 ##### ##### ##### ##### ##### ##### ##### ##### ##### ##### ##### ##### ##### ##### ##### #####
858
859 sub scrape { my ($self, $content, $debug, $scraperFrame, $hit) = @_;
860 $scraperFrame = $self->scraperFrame() unless $scraperFrame;
861 for (${$scraperFrame}[0]) {
862 return $self->scraperHTML($scraperFrame, \$content, $hit, $debug) if m/HTML/;
863 return $self->scraperTidyXML($scraperFrame, \$content, $hit, $debug) if m/TidyXML/;
864 }
865 die "Scraper mode '${$scraperFrame}[0]' is not implemented in version $VERSION of Scraper.pm for ".ref($self)."\n";
866 }
867
868 # private
869 sub scraperHTML { my ($self, $scaffold_array, $content, $hit, $debug) = @_;
870 my $TidyXML = new WWW::Scraper::TidyXML($self, $content, {'frameType' => 'HTML', 'artifactFolder' => $self->artifactFolder()});
871 $self->_tidyXmlObject($TidyXML);
872 $TidyXML->m_asString($content);
873 return $self->scraper($$scaffold_array[1], $TidyXML, $hit, $debug);
874 }
875
876 # private
877 sub scraperTidyXML { my ($self, $scaffold_array, $content, $hit, $debug) = @_;
878 # Execute any preprocessors this TidyXML may declare.
879 my $i = 1;
880 while ( 'ARRAY' ne ref $$scaffold_array[$i] ) {
881 my $datParser = $$scaffold_array[$i];
882 $i += 1;
883 $content = &$datParser($self, $hit, $content);
884 }
885 my $TidyXML = new WWW::Scraper::TidyXML($self, $content, {'frameType' => 'TidyXML', 'artifactFolder' => $self->artifactFolder()});
886 $self->_tidyXmlObject($TidyXML);
887 return $self->scraper($$scaffold_array[$i], $TidyXML, $hit, $debug);
888 }
889
890
891 # private
892 sub scraperRecurse { my ($self, $sub_string, $next_scaffold, $TidyXML, $hit, $debug) = @_;
893
894 my $myTidyXML = $TidyXML;
895 my ($saveContext, $saveFoundContext, $saveString);
896 if ( $myTidyXML ) {
897 $saveContext = $TidyXML->m_context();
898 $saveFoundContext = $TidyXML->m_found_context();
899 $myTidyXML->m_context($TidyXML->m_found_context);
900 $saveString = $myTidyXML->m_asString();
901 if ( $$sub_string ) {
902 $myTidyXML->m_asString($sub_string);
903 }
904 } else {
905 $myTidyXML = new WWW::Scraper::TidyXML;
906 $myTidyXML->m_asString($sub_string);
907 }
908
909 unshift @HitStack, $hit;
910 my $total_hits_found = $self->scraper($next_scaffold, $myTidyXML, $hit, $debug);
911 shift @HitStack;
912
913 $myTidyXML->m_context($saveContext);
914 $myTidyXML->m_found_context($saveFoundContext);
915 $myTidyXML->m_asString($saveString);
916
917 return $total_hits_found;
918 }
919
920 # private
921 sub scraperRecurseAndChop { my ($self, $sub_string, $next_scaffold, $TidyXML, $hit, $debug) = @_;
922
923 my $myTidyXML = $TidyXML;
924 my ($saveContext, $saveFoundContext, $saveString);
925 if ( $myTidyXML ) {
926 ($saveContext,$saveFoundContext,$saveString) = ($TidyXML->m_context(),$TidyXML->m_found_context(),$myTidyXML->m_asString());
927 $myTidyXML->m_context($TidyXML->m_found_context);
928 if ( $$sub_string ) {
929 $myTidyXML->m_asString($sub_string);
930 }
931 } else {
932 $myTidyXML = new WWW::Scraper::TidyXML;
933 $myTidyXML->m_asString($sub_string);
934 }
935
936 unshift @HitStack, $hit;
937 my $total_hits_found = $self->scraper($next_scaffold, $myTidyXML, $hit, $debug);
938 shift @HitStack;
939
940 $myTidyXML->m_context($saveContext);
941 $myTidyXML->m_found_context($saveFoundContext);
942 $myTidyXML->m_asString($saveString);
943
944 return $total_hits_found;
945 }
946
947 # private
948 sub scraper { my ($self, $scaffold_array, $TidyXML, $hit, $debug) = @_;
949
950 # Here are some variables that we use frequently done here.
951 my $total_hits_found = 0; # counts hits, and is boolean for "any-hit-found".
952
953 my $sub_string = undef;
954 my $next_scaffold = undef;
955 my $attributes = undef;
956 $TidyXML->m_TRACE($self->{'_traceFlags'}) if $TidyXML;
957
958 my (@ary,@dts); # 'F' and 'REGEX' are co-functional, so we need these shared variables here.
959
960 SCAFFOLD: for my $scaffold ( @$scaffold_array ) {
961 my $tag = $$scaffold[0];
962
963 # 'HIT*' is special since it has pre- and post- processing (adding the hits to the hit-list).
964 # All other tokens simply process data as it moves along, then they're done,
965 # so they will do a set up, then pass along to recurse on scraper() . . .
966 if ( ref($tag) ) {
967 $hit->_hitfound(0) if defined $hit;
968 ($next_scaffold, $sub_string, $attributes) = $tag->scrape($self, $scaffold, $TidyXML, $hit);
969
970 #$hit->name(\$attributes->{'name'}); # for ScraperDiscovery
971 #$hit->content(\$sub_string); # for ScraperDiscovery
972 #$hit->name(\$attributes->{'name'});
973 #$hit->action(\$attributes->{'action'});
974 #$hit->method(\$attributes->{'method'});
975 #$hit->caption($caption) if $attributes->{'type'} =~ m{^radio|checkbox$}i;
976 #$hit->name(\$attributes->{'name'});
977 #$hit->type(\$attributes->{'type'});
978 #$hit->value(\$attributes->{'value'});
979 #$hit->background(\$attributes->{'background'});
980 #$hit->bgcolor(\$attributes->{'bgcolor'});
981
982 $total_hits_found = 1 if defined $hit && $hit->_hitfound;
983 $sub_string = ${$TidyXML->asString()} if $next_scaffold && !defined($sub_string);
984 next SCAFFOLD unless $sub_string;
985 }
986 elsif ( 'HIT' eq $tag ) {
987 $self->{'total_hits_count'} = 1;
988 my $resultType = $$scaffold[1];
989 if ( 'ARRAY' eq ref $resultType ) {
990 $next_scaffold = $resultType;
991 $resultType = $self->GetResponseClass();
992 }
993 $next_scaffold = $$scaffold[2];
994 $next_scaffold = $$scaffold[1] unless defined $next_scaffold;
995 }
996 elsif ( 'HIT*' eq $tag )
997 {
998 my $resultType = $$scaffold[1];
999 if ( 'ARRAY' eq ref $resultType ) {
1000 $next_scaffold = $resultType;
1001 $resultType = $self->GetResponseClass();
1002 }
1003 else
1004 {
1005 $next_scaffold = $$scaffold[2];
1006 }
1007 $next_scaffold = $$scaffold[2];
1008 $next_scaffold = $$scaffold[1] unless defined $next_scaffold;
1009 my $hit;
1010 do
1011 {
1012 $self->{'total_hits_count'} += 1;
1013 print "HIT number ".$self->{'total_hits_count'}."\n" if ($self->ScraperTrace('d'));
1014 if ( $hit && $self->postSelect($self->GetRequest(), $hit) )
1015 {
1016 $self->_AddToHitList($hit); #push @{$self->{cache}}, $hit;
1017 $total_hits_found += 1;
1018 }
1019 $hit = $self->newHit($resultType, $next_scaffold, $self->scraperDetail()?$self->scraperDetail()->[1]:undef);
1020 } while ( $self->scraperRecurse($TidyXML->asString(), $next_scaffold, $TidyXML, $hit, $debug) );
1021 next SCAFFOLD;
1022 }
1023
1024 elsif ( 'BODY' eq $tag )
1025 {
1026 $sub_string = undef;
1027 if ( $$scaffold[1] and $$scaffold[2] ) {
1028 ${$TidyXML->asString()} =~ s-$$scaffold[1](.*?)$$scaffold[2]--si; # Strip off the adminstrative clutter at the beginning and end.
1029 $sub_string = $1;
1030 } elsif ( $$scaffold[1] ) {
1031 ${$TidyXML->asString()} =~ s-$$scaffold[1](.*)$-$1-si; # Strip off the adminstrative clutter at the beginning.
1032 $sub_string = $1;
1033 } elsif ( $$scaffold[2] ) {
1034 ${$TidyXML->asString()} =~ s-^(.*?)$$scaffold[2]-$1-si; # Strip off the adminstrative clutter at the end.
1035 $sub_string = $1;
1036 } else {
1037 next SCAFFOLD;
1038 }
1039 if ( 'ARRAY' ne ref $$scaffold[3] ) # if next_scaffold is an array ref, then we'll recurse (below)
1040 {
1041 next SCAFFOLD unless $sub_string;
1042
1043 my $binding = $$scaffold[3];
1044 my $datParser = $$scaffold[4];
1045 $datParser = \&WWW::Scraper::trimTags unless $datParser;
1046 if ( $binding eq 'url' )
1047 {
1048 my $url = new URI::URL(&$datParser($self, $hit, $sub_string), $self->{_base_url});
1049 $url = $url->abs();
1050 $hit->plug_url($url);
1051 }
1052 elsif ( $binding) {
1053 my $dat = &$datParser($self, $hit, $sub_string);
1054 $hit->plug_elem($binding, $dat) if defined $dat;
1055 }
1056 $total_hits_found = 1;
1057 next SCAFFOLD;
1058 } else {
1059 $next_scaffold = $$scaffold[3];
1060 }
1061 }
1062
1063 elsif ( 'DATA' eq $tag )
1064 {
1065 $sub_string = '';
1066 if ( $$scaffold[1] and $$scaffold[2] ) {
1067 ${$TidyXML->asString()} =~ s-$$scaffold[1](.*?)$$scaffold[2]--si;
1068 $sub_string = $1;
1069 } else {
1070 next SCAFFOLD;
1071 }
1072 my $binding = $$scaffold[3];
1073 $hit->plug_elem($binding, $sub_string) if defined $sub_string;
1074 $total_hits_found = 1;
1075 next SCAFFOLD;
1076 }
1077
1078 elsif ( 'COUNT' eq $tag )
1079 {
1080 #$self->approximate_result_count(0);
1081 if ( ${$TidyXML->asString()} =~ m/$$scaffold[1]/si )
1082 {
1083 print STDERR "approximate_result_count: '$1'\n" if ($self->ScraperTrace('d'));
1084 $self->approximate_result_count ($1);
1085 }
1086 else {
1087 print STDERR "Can't find COUNT: '$$scaffold[1]'\n" if ($self->ScraperTrace('d'));
1088 }
1089 next SCAFFOLD;
1090 }
1091
1092 elsif ( 'HTML' eq $tag )
1093 {
1094 ${$TidyXML->asString()} =~ m-<HTML>(.*)</HTML>-si;
1095 $sub_string = $1;
1096 $next_scaffold = $$scaffold[1];
1097 }
1098
1099 elsif ( $tag =~ m/^(TABLEX|TRX|DL)$/ )
1100 {
1101 my $tagLength = length ($tag) + 2;
1102 my $elmName = $$scaffold[1];
1103 $elmName = '#0' unless $elmName;
1104 if ( 'ARRAY' eq ref $$scaffold[1] )
1105 {
1106 $next_scaffold = $$scaffold[1];
1107 }
1108 elsif ( $elmName =~ /^#(\d*)$/ )
1109 {
1110 for (1..$1)
1111 {
1112 $TidyXML->getMarkedText($tag); # and throw it away.
1113 }
1114 $next_scaffold = $$scaffold[2];
1115 }
1116 else {
1117 print STDERR "elmName: $elmName\n" if ($self->ScraperTrace('d'));
1118 $next_scaffold = $$scaffold[2];
1119 die "Element-name form of <$tag> is not implemented, yet.";
1120 }
1121 next SCAFFOLD unless $sub_string = $TidyXML->getMarkedText($tag);
1122 }
1123
1124
1125 elsif ( 'TAG' eq $tag )
1126 {
1127 next SCAFFOLD unless $sub_string = $TidyXML->getMarkedText($$scaffold[1]); # and throw it away.
1128 $next_scaffold = $$scaffold[2];
1129 if ( 'ARRAY' ne ref $next_scaffold ) # if next_scaffold is an array ref, then we'll recurse (below)
1130 {
1131 my $binding = $next_scaffold;
1132 my $datParser = $$scaffold[3];
1133 print STDERR "raw dat: '$sub_string'\n" if ($self->ScraperTrace('d'));
1134 if ( $self->ScraperTrace('d') ) {
1135 print STDERR "datParser: ".ref($datParser)."\n";
1136 };
1137 $datParser = \&WWW::Scraper::trimTags unless $datParser;
1138 print STDERR "binding: '$binding', " if ($self->ScraperTrace('d'));
1139 print STDERR "parsed dat: '".&$datParser($self, $hit, $sub_string)."'\n" if ($self->ScraperTrace('d'));
1140 if ( $binding eq 'url' )
1141 {
1142 my $url = new URI::URL(&$datParser($self, $hit, $sub_string), $self->{_base_url});
1143 $url = $url->abs();
1144 $hit->plug_url($url);
1145 }
1146 elsif ( $binding) {
1147 my $dat = &$datParser($self, $hit, $sub_string);
1148 $hit->plug_elem($binding, $dat) if defined $dat;
1149 }
1150 $total_hits_found = 1;
1151 next SCAFFOLD;
1152 }
1153 }
1154 elsif ( $tag =~ m/^(TDX|DT|DD|DIV|SPAN)$/ )
1155 {
1156 next SCAFFOLD unless $sub_string = $TidyXML->getMarkedText($tag); # and throw it away.
1157 $next_scaffold = $$scaffold[1];
1158 if ( 'ARRAY' ne ref $next_scaffold ) # if next_scaffold is an array ref, then we'll recurse (below)
1159 {
1160 my $binding = $next_scaffold;
1161 my $datParser = $$scaffold[2];
1162 print STDERR "raw dat: '$sub_string'\n" if ($self->ScraperTrace('d'));
1163 if ( $self->ScraperTrace('d') ) { # print ref $ aways does something screwy
1164 print STDERR "datParser: ";
1165 print STDERR ref $datParser;
1166 print STDERR "\n";
1167 };
1168 $datParser = \&WWW::Scraper::trimTags unless $datParser;
1169 print STDERR "binding: '$binding', " if ($self->ScraperTrace('d'));
1170 print STDERR "parsed dat: '".&$datParser($self, $hit, $sub_string)."'\n" if ($self->ScraperTrace('d'));
1171 next SCAFFOLD unless $binding;
1172 if ( $binding eq 'url' )
1173 {
1174 my $url = new URI::URL(&$datParser($self, $hit, $sub_string), $self->{_base_url});
1175 $url = $url->abs();
1176 $hit->plug_url($url);
1177 }
1178 elsif ( $binding) {
1179 my $dat = &$datParser($self, $hit, $sub_string);
1180 $hit->plug_elem($binding, $dat) if defined $dat;
1181 }
1182 $total_hits_found = 1;
1183 next SCAFFOLD;
1184 }
1185 }
1186 elsif ( 'AX' eq $tag )
1187 {
1188 my $lbl = $$scaffold[1];
1189 my $anchor;
1190 next SCAFFOLD unless ($sub_string, $anchor) = $TidyXML->getMarkedText('A'); # and throw it away.
1191 next SCAFFOLD unless $anchor;
1192 if ( ( $anchor =~ s-A\s.*?HREF=(["'])([^"']+)\1--si) or
1193 ( $anchor =~ s-A\s.*?HREF(=)([^> ]+)--si)
1194 )
1195 {
1196 print "<A> binding: $$scaffold[2]: '$sub_string', $$scaffold[1]: '$2'\n" if ($self->ScraperTrace('d'));
1197 my $datParser = $$scaffold[3];
1198 $datParser = \&WWW::Scraper::trimTags unless $datParser;
1199 my $dat = &$datParser($self, $hit, $sub_string);
1200 $hit->plug_elem($$scaffold[2], $dat) if defined $dat;
1201
1202 my ($url) = new URI::URL($2, $self->{_base_url});
1203 $url = $url->abs();
1204 if ( $lbl eq 'url' ) {
1205 $url = WWW::Scraper::unescape_query($url) if $TidyXML->m_isTidyd();
1206 $hit->plug_url($url);
1207 }
1208 else {
1209 $hit->plug_elem($lbl, $url) if defined $url;
1210 }
1211 $total_hits_found = 1;
1212 }
1213 next SCAFFOLD;
1214 }
1215 elsif ( 'AN' eq $tag )
1216 {
1217 my $lbl = $$scaffold[1];
1218 if ( ${$TidyXML->asString()} =~ s-<A[^>]+?HREF=([^>]+)>(.*?)</A>--si )
1219 {
1220 print "<A> binding: $$scaffold[2]: '$2', $$scaffold[1]: '$1'\n" if ($self->ScraperTrace('d'));
1221
1222 my $datParser = $$scaffold[3];
1223 $datParser = \&WWW::Scraper::trimTags unless $datParser;
1224 my $dat = &$datParser($self, $hit, $2);
1225 $hit->plug_elem($$scaffold[2], $dat) if defined $dat;
1226
1227 my ($url) = new URI::URL($1, $self->{_base_url});
1228 $url = $url->abs();
1229 if ( $lbl eq 'url' ) {
1230 $url = WWW::Scraper::unescape_query($url) if $TidyXML->m_isTidyd();
1231 $hit->plug_url($url);
1232 }
1233 else {
1234 $hit->plug_elem($lbl, $url) if defined $url;
1235 }
1236 $total_hits_found = 1;
1237 }
1238 next SCAFFOLD;
1239 }
1240 elsif ( 'AQ' eq $tag )
1241 {
1242 my $lbl = $$scaffold[2];
1243 my $anchor;
1244 next SCAFFOLD unless ($sub_string, $anchor) = $TidyXML->getMarkedText('A',$$scaffold[1]); # and throw it away.
1245 next SCAFFOLD unless $anchor;
1246 if ( ( $anchor =~ s-A\s.*?HREF=(["'])([^"']+)\1--si) or
1247 ( $anchor =~ s-A\s.*?HREF(=)([^> ]+)--si)
1248 )
1249 {
1250 print "<AQ> binding: $$scaffold[3]: '$sub_string', $$scaffold[2]: '$2'\n" if ($self->ScraperTrace('d'));
1251 my $datParser = $$scaffold[4];
1252 $datParser = \&WWW::Scraper::trimTags unless $datParser;
1253 my $dat = &$datParser($self, $hit, $sub_string);
1254 $hit->plug_elem($$scaffold[3], $dat) if defined $dat;
1255
1256 my ($url) = new URI::URL($2, $self->{_base_url});
1257 $url = $url->abs();
1258 if ( $lbl eq 'url' ) {
1259 $url = WWW::Scraper::unescape_query($url) if $TidyXML->m_isTidyd();
1260 $hit->plug_url($url);
1261 }
1262 else {
1263 $hit->plug_elem($lbl, $url) if defined $url;
1264 }
1265 $total_hits_found = 1;
1266 }
1267 next SCAFFOLD;
1268 } elsif ( $tag eq 'SNIP' ) { # another idea: 'CROP', the inverse of 'SNIP' - gdw.2003.01.16
1269 $sub_string = ${$TidyXML->asString()};
1270 my $matchString = $$scaffold[1];
1271 if ( 'ARRAY' eq ref $matchString ) {
1272 $next_scaffold = $matchString;
1273 $matchString = '';
1274 } else {
1275 $next_scaffold = $$scaffold[2];
1276 }
1277 $sub_string =~ s{$matchString}{}gsi;
1278
1279 } elsif ( $tag eq 'RESIDUE' )
1280 {
1281 $sub_string = ${$TidyXML->asString()};
1282 my $binding = $$scaffold[1];
1283 my $datParser = $$scaffold[2];
1284 $datParser = \&WWW::Scraper::null unless $datParser;
1285 my $dat = &$datParser($self, $hit, $sub_string);
1286 $hit->plug_elem($binding, $dat) if defined $dat;
1287 next SCAFFOLD;
1288
1289 } elsif ( $tag eq 'FOR' ) {
1290 my $iterator = $$scaffold[1];
1291 my $iterationString = $$scaffold[2];
1292 $next_scaffold = $$scaffold[3];
1293 my ($i,$j) = ($iterationString =~ m/^(\d+)\.\.(\d+)$/);
1294 for my $itr ($i..$j) {
1295 $self->_forInterator($itr);
1296 $total_hits_found += $self->scraperRecurse(\$sub_string, $next_scaffold, $TidyXML, $hit, $debug);
1297 }
1298 } elsif ( $tag eq 'XPath' )
1299 {
1300 my $xpath = $$scaffold[1];
1301 if ( $xpath =~ /for\((\w+)?\)/i ) {
1302 my $forN = $self->_forInterator();
1303 $xpath =~ s/for\((\w+)?\)/$forN/i;
1304 }
1305 if ( $xpath =~ /hit\((\d+)?\)/i ) {
1306 my $hitN = $self->{'total_hits_count'} + ($1||0);
1307 $xpath =~ s/hit\((\d+)?\)/$hitN/i;
1308 }
1309 my $binding = $$scaffold[2];
1310 $sub_string = ${$TidyXML->asString($xpath)}; # This also sets m_found_context, for recursing.
1311 next SCAFFOLD unless $sub_string;
1312 if ( 'ARRAY' eq ref $binding ) {
1313 $sub_string = undef; # We don't need sub_string for recursing.
1314 $next_scaffold = $binding;
1315 } elsif ( defined $$scaffold[2] ) {
1316 my $i = 3;
1317 while ( $$scaffold[$i] and 'ARRAY' ne ref $$scaffold[$i] ) {
1318 my $datParser = $$scaffold[$i];
1319 $i += 1;
1320 $sub_string = &$datParser($self, $hit, $sub_string);
1321 }
1322 print "<XPath> binding: $binding: $sub_string\n" if ($self->ScraperTrace('d'));
1323 $hit->plug_elem($binding, $sub_string) if defined $sub_string;
1324 $total_hits_found = 1;
1325 next SCAFFOLD;
1326 } else {
1327 next SCAFFOLD;
1328 }
1329
1330 } elsif ( $tag eq 'CLEANUP' )
1331 {
1332 my $i = 1;
1333 my $content = $TidyXML->asString();
1334 while ( $$scaffold[$i] and ('ARRAY' ne ref $$scaffold[$i]) ) {
1335 my $datParser = $$scaffold[$i];
1336 $i += 1;
1337 $content = &$datParser($self, $hit, $content);
1338 }
1339 $TidyXML->m_asString($content);
1340 }
1341 elsif ( $tag eq 'BOGUS' )
1342 {
1343 # Take back any hits at the header that are declared to be "bogus".
1344 my $bogusCount = $$scaffold[1];
1345 do { for ( 1..$bogusCount ) {
1346 last unless $total_hits_found > 0;
1347 $total_hits_found -= 1;
1348 shift @{$self->{cache}};
1349 }
1350 } if $bogusCount > 0;
1351 # Take back any hits at the footer that are declared to be "bogus".
1352 do { for ( 1..(-$bogusCount) ) {
1353 last unless $total_hits_found > 0;
1354 $total_hits_found -= 1;
1355 pop @{$self->{cache}};
1356 }
1357 } if $bogusCount < 0;
1358 next SCAFFOLD;
1359 }
1360 elsif ( $tag eq 'TRACE' )
1361 {
1362 my $x = ${$TidyXML->asString()};
1363 $x =~ s/\r//gs;
1364 print STDERR "TRACE:\n'$x'\n";
1365 $total_hits_found += $$scaffold[1];
1366 }
1367 elsif ( $tag eq 'CALLBACK' ) { # deprecated by WWW::Scraper::Opcodecode - gdw.2003.03.14
1368 ($sub_string, $next_scaffold) = &{$$scaffold[1]}($self, $hit, $TidyXML->asString(), $scaffold, \$total_hits_found);
1369 }
1370 else {
1371 die "Unrecognized ScraperFrame option: '$tag'";
1372 }
1373
1374 next SCAFFOLD unless $next_scaffold;
1375 $total_hits_found += $self->scraperRecurse(\$sub_string, $next_scaffold, $TidyXML, $hit, $debug);
1376 }
1377 return $total_hits_found;
1378 }
1379
1380
1381 # private
1382 sub newHit {
1383 my ($self, $resultType, $scraperFrame, $scraperDetailFrame) = @_;
1384 my $hit;
1385 if ( 'CODE' eq ref $resultType ) {
1386 $hit = &$resultType();
1387 } else {
1388 my $subResultType = undef; # Set up for Response::generic to build a properly named Response class.
1389 unless ( $resultType ) {
1390 $resultType = 'generic';
1391 ($subResultType) = (ref($self) =~ m{([^:]+)$});
1392 }
1393 eval "\$hit = new WWW::Scraper::Response::$resultType\::new(\$scraperFrame, \$scraperDetailFrame, \$subResultType);";
1394 if ( $@ ) {
1395 eval "use WWW::Scraper::Response::$resultType; \$hit = new WWW::Scraper::Response::$resultType(\$scraperFrame, \$scraperDetailFrame, \$subResultType);";
1396 if ( $@ ) {
1397 print "Can't require Response subclass '$resultType': $@\n";
1398 return undef;
1399 }
1400 }
1401 }
1402 unless ( $hit ) {
1403 die "Can't instantiate your Response module '$resultType': $@";
1404 }
1405 $hit->_ScraperEngine($self);
1406 $hit->_searchObject($self);
1407
1408 return $hit;
1409 }
1410
1411 # private
1412 sub _AddToHitList {
1413 my ($self, $hit) = @_;
1414
1415 if ( my $parentHit = $HitStack[0] ) {
1416 $parentHit->_AddToHitList($hit);
1417 } else {
1418 push @{$self->{'cache'}}, $hit;
1419 }
1420 }
1421 # private
1422 sub _AddToHitStack {
1423 }
1424
1425 sub touchUp {
1426 my ($self, $hit, $dat, $datParser) = @_;
1427 }
1428
1429
1430 # Returns the marked up text from the referenced string, as designated by the given tag.
1431 # This algorithm extracts the contents of the first <$tag> element it encounters,
1432 # taking into consideration that it may contain <$tag> elements within it.
1433 # It removes the marked text from the original string, strips off the markup tags,
1434 # and returns that result.
1435 # (if wantarray, will return result and first tag, with brackets removed)
1436 #
1437 sub getMarkedText {
1438 my ($self, $tag, $content, $withContent) = @_;
1439
1440 my $eidx = 0;
1441 my $sidx = -1;
1442 my $depth = 0;
1443
1444 # while ( $$content =~ m-<(/)?$tag[^>]*?>-gsi ) {
1445 while ( $$content =~ m-<(/)?$tag(\s[^>]*?)?>-gsi ) {
1446 if ( $1 ) { # then we encountered an end-tag
1447 $depth -= 1;
1448 if ( $depth < 0 ) {
1449 # . . . then somehow we've stumbled into the midst of a table whose end-tag
1450 # has just been encountered - let's be generous and start over.
1451 $eidx = 0;
1452 $sidx = -1;
1453 $depth = 0;
1454 }
1455 elsif ( $depth == 0 ) { # we've counted as many end-tags as start-tags; we're done!
1456 $eidx = pos $$content;
1457 if ( $withContent ) {
1458 my $rslt = substr $$content, $sidx, $eidx - $sidx;
1459 my (undef, undef, $txt) = ($rslt =~ m-^<($tag(\s[^>]*?)?)>(.*?)</$tag\s*[^>]*?>$-si);
1460 unless ($txt =~ m{$withContent}si) {
1461 $eidx = 0;
1462 $sidx = -1;
1463 $depth = 0;
1464 next;
1465 }
1466 }
1467 last;
1468 }
1469 } else # we encountered a start-tag
1470 {
1471 $depth += 1;
1472 $sidx = length $` unless $sidx >= 0;
1473 if ( ($tag eq 'BR') && ($depth == 2) ) {
1474 $eidx = pos $$content;
1475 last;
1476 }
1477 }
1478 }
1479
1480
1481 return undef if $sidx < 0;
1482 my $rslt = substr $$content, $sidx, $eidx - $sidx, '';
1483 $$content =~ m/./;
1484 # $rslt =~ m-^<($tag[^>]*?)>(.*?)</$tag\s*[^>]*?>$-si;
1485 $rslt =~ m-^<($tag(\s[^>]*?)?)>(.*?)</?$tag\s*[^>]*?>$-si;
1486 return ($3, $1) if wantarray;
1487 return $3;
1488 }
1489
1490
1491 sub addURL {
1492 my ($self, $hit, $dat) = @_;
1493
1494 if ( $dat =~ m-<A\s+HREF="([^"]+)"[^>]*>-si )
1495 {
1496 my ($url) = new URI::URL($1, $self->{_base_url});
1497 $url = $url->abs();
1498 $hit->plug_url($url);
1499 } else
1500 {
1501 $hit->plug_url("Can't find HREF in '$dat'");
1502 }
1503
1504 return trimTags($self, $hit, $dat);
1505 }
1506
1507 # trimTags($hit, $dat) - Strip tag clutter from $dat, in the context of $hit.
1508 # trimTags($hit, $dat) - Strip double-LFs, then trim the tag clutter from $_;
1509 # Note: "ref-not-ref" interface on $dat -
1510 # $dat may be a string, or a reference to a string.
1511 # if string, trimLFLFs() returns string, if ref, trimLFLFs() uses and returns ref.
1512 sub trimTags {
1513 my ($self, $hit, $dat) = @_;
1514 return undef unless defined $dat;
1515 return $dat unless $dat;
1516 my $dt;
1517 my $isRef=0;
1518 if ( ref($dat) ) {
1519 $isRef = 1;
1520 } else {
1521 $dt = $dat;
1522 $dat = \$dt;
1523 }
1524 $$dat =~ s{<br>}{\n}gi;
1525 $$dat =~ s{\r}{}gsi;
1526 $$dat =~ s{</?[^>]+>}{}gsi;
1527 $$dat =~ s/&nbsp;/ /gs;
1528 $$dat =~ s{&lt;}{>}g;
1529 $$dat =~ s{&gt;}{>}g;
1530 $$dat =~ s{&quot;}{\042}gs;
1531
1532 return $isRef?$dat:$$dat;
1533 }
1534
1535 sub trimLFs { # Strip LFs, then tag clutter from $_;
1536 my ($self, $hit, $dat) = @_;
1537 $dat = $self->trimTags($hit, $dat);
1538 $dat =~ s/\s*\r?\n\s*//gs;
1539 # This simply rearranges the parameter list from the datParser form.
1540 return $dat;
1541 }
1542
1543
1544 # trimLFLFs($hit, $dat) - Strip double-LFs, then trim the tag clutter from $_;
1545 # Note: "ref-not-ref" interface on $dat -
1546 # $dat may be a string, or a reference to a string.
1547 # if string, trimLFLFs() returns string, if ref, trimLFLFs() uses and returns ref.
1548 sub trimLFLFs {
1549 my ($self, $hit, $dat) = @_;
1550 my $dt;
1551 my $isRef=0;
1552 if ( ref($dat) ) {
1553 $isRef = 1;
1554 } else {
1555 $dt = $dat;
1556 $dat = \$dt;
1557 }
1558 $dat = $self->trimTags($hit, $dat);
1559 # while (
1560 $$dat =~ s/[\s]*\n([\s]*\n[\s]*)*/\n/gsi;
1561 # ) {}; # Do several times, rather than /g, to handle triple, quadruple, quintuple, etc.
1562 # This simply rearranges the parameter list from the datParser form.
1563 return $isRef?$dat:$$dat;
1564 }
1565
1566 # XML::XPath seems to keep a blank, the attribute name, and the '=' sign in the result.
1567 # Is this standard XPath conventions? useless to us, though.
1568 sub trimXPathAttr {
1569 my ($self, $hit, $dat) = @_;
1570 $dat =~ s/^ \w+?=(['"])(.*)\1$/$2/;
1571 return $dat;
1572 }
1573 # This does trimXPathAttr, then converts the result to an absolute URL.
1574 sub trimXPathHref {
1575 my ($self, $hit, $dat) = @_;
1576 $dat =~ m/^ \w+?=(['"])(.*)\1$/;
1577 my ($url) = new URI::URL($2, $self->{_base_url});
1578 $url = $url->abs();
1579 $url = WWW::Scraper::unescape_query($url);
1580 return $url;
1581 }
1582
1583 sub trimComments { # Strip comments from $_.
1584 my ($self, $hit, $dat) = @_;
1585 $dat =~ s/<!--.*?-->//gs;
1586 return $dat;
1587 }
1588
1589
1590 sub removeScriptsInHTML {
1591 my ($self, $hit, $xml) = @_;
1592
1593 # Strip out some regions that contain no information, but might be ill-formed output of "Tidy".
1594 my $removedScripts;
1595 for my $tag ( qw( script noscript ) ) {
1596 while ( $$xml =~ s-(<$tag.*?</$tag>)--si ) {
1597 $removedScripts .= $1;
1598 }
1599 }
1600 $self->{'removedScripts'} = \$removedScripts;
1601
1602 return $xml;
1603 }
1604
1605 # Remove everything between </HEAD> and <BODY> - this confuses TidyXML.
1606 sub cleanupHeadBody {
1607 my ($self, $hit, $xml) = @_;
1608 $$xml =~ s-<html>(.*)<head>-<html><head>-gsi;
1609 $$xml =~ s-</head>(.*)<body>-</head><body>-gsi;
1610 $self->{'cleanedupHeadBody'} = \$1;
1611 return $xml;
1612 }
1613
1614 # A null filter.
1615 sub null { # Strip tag clutter from $_;
1616 my ($self, $hit, $dat) = @_;
1617 return $dat;
1618 }
1619
1620 # Alternative name for the next_result() method for Scraper.
1621 sub next_response {
1622 my $self = shift;
1623 if ( my $oSearch = $self->_wwwSearchBackend() ) {
1624 $self->SetRequest( new WWW::Scraper::Request($self, $self->{'native_query'}, $self->{'native_options'}) ) unless ( $self->GetRequest());
1625 ($oSearch->{'native_query'}, $oSearch->{'native_options'}) = ($self->GetRequest()->_native_query(), $self->{'native_options'});
1626 return $oSearch->next_result(@_);
1627 }
1628 $self->{'native_query'} = '' unless defined($self->{'native_query'}); # Prevent "search not yet specified" in WWW::Search::next_result().
1629 $self->next_result(@_);
1630 }
1631
1632 # Alternative name for the results() method for Scraper.
1633 sub responses {
1634 my $self = shift;
1635 $self->results(@_);
1636 }
1637
1638 # Alternative name for the native_query() method for Scraper.
1639 sub setup_query {
1640 my $self = shift;
1641 $self->native_query(@_);
1642 }
1643 sub native_query {
1644 my $self = shift;
1645 delete $self->{'_scraperRequest'};
1646 $self->{'native_query'} = '' unless defined($self->{'native_query'}); # Prevent "search not yet specified" in WWW::Search::next_result().
1647 $self->SUPER::native_query(@_);
1648 }
1649
1650
1651
1652 # #######################################################################################
1653 # Get the Next URL from a <form> on the page.
1654 # Sometimes there's just a NEXT form, sometimes there's a PREV form and a NEXT form . . .
1655 use HTML::Form;
1656 sub findNextForm {
1657 my ($self, $hit, $dat) = @_;
1658
1659 my $next_content = $dat;
1660 while ( my ($sub_content, $frm) = $self->getMarkedText('FORM', \$next_content) ) {
1661 last unless $sub_content;
1662 #warn "\n\n\n\nFORM:\n$sub_content";
1663 # Reconstruct the form that contains the NEXT data.
1664 my @forms = HTML::Form->parse("<form $frm>$sub_content</form>", $self->{'_base_url'});
1665 my $form = $forms[0];
1666
1667 my $submit_button;
1668 for ( $form->inputs() ) {
1669 if ( $_->value() =~ m/Next/ ) {
1670 $submit_button = $_;
1671 last;
1672 }
1673 }
1674 if ( $submit_button ) {
1675 my $req = $submit_button->click($form); #
1676 return $req->uri();
1677 }
1678 }
1679 return undef;
1680 }
1681
1682 # #######################################################################################
1683 # Get the Next URL from a <form> on the page.
1684 # Sometimes there's just a NEXT form, sometimes there's a PREV form and a NEXT form . . .
1685 sub findNextFormInXML {
1686 my ($self, $hit, $dat) = @_;
1687
1688 my $next_content = $dat;
1689 while ( my ($sub_content, $frm) = $self->getMarkedText('FORM', \$next_content) ) {
1690 last unless $sub_content;
1691 # Reconstruct the form that contains the NEXT data.
1692 my $asHTML = "<form $frm>$sub_content</form>";
1693 $asHTML =~ s-/>->-gs;
1694 my @forms = HTML::Form->parse($asHTML, $self->{'_base_url'});
1695 my $form = $forms[0];
1696
1697 my $submit_button;
1698 for ( $form->inputs() ) {
1699 if ( $_->value() =~ m/Next/ ) {
1700 $submit_button = $_;
1701 last;
1702 }
1703 }
1704 if ( $submit_button ) {
1705 my $req = $submit_button->click($form); #
1706 return $req->uri();
1707 }
1708 }
1709 return undef;
1710 }
1711
1712 sub unescape_query {
1713 # code stolen, and enhanced, from URI::Escape.pm.
1714 my @copy = @_;
1715 for (@copy) {
1716 s/\+/ /g;
1717 s/\&amp;/&/g;
1718 s/%([\dA-Fa-f]{2})/chr(hex($1))/eg;
1719 }
1720 return wantarray ? @copy : $copy[0];
1721 }
1722
1723 # ContentAnalysis()
1724 # This method looks at general HTML content and pulls out as much relevant information as it can.
1725 sub ContentAnalysis {
1726 my ($self) = @_;
1727
1728 return \"" unless $self->response();
1729 my $dat = $self->response()->content;
1730 my $rDat = $self->trimLFLFs(undef, \$dat);
1731 return $rDat;
1732 }
1733
1734 1;
1735
1736 __END__
« WWW/Scraper/ScraperDiscovery.pm ↑ Summary WWW/Scraper/Opcode/TR.pm »