WWW/Scraper/Response.pm untested

filter: Statementstmt 0.0% 0 / 285 Branchbran 0.0% 0 / 172 Conditioncond 0.0% 0 / 52 MC/DCmcdc 0.0% 0 / 29 Subroutinesub 0.0% 0 / 22 Podpod 0.0% 0 / 17 totaltotal 0.0% 0 / 577 CC 86 SCAR 63.5
CC
86
Cov
0%
fieldCapture
1406.0
new
306.0
asHtml
210.0
CRAP 573.3
1 package WWW::Scraper::Response;
2  
3 =head1 NAME
4  
5 WWW::Scraper::Response - Response class of generic scrapes.
6  
7 =head1 SYNOPSIS
8  
9 use WWW::Scraper('engineName');
10 #
11 my $scraper = new WWW::Scraper('engineName');
12 my $response = $scraper->Response();
13 #
14 my $field = $response->$fieldName();
15 # or
16 my $field = $scraper->Response->$fieldName();
17 #
18 # or, specify your own Response class.
19 my $scraper = new WWW::Scraper('engineName', 'responseClass');
20 my $field = $scraper->Response->$fieldName();
21  
22 =head1 DESCRIPTION
23  
24 Scraper automatically generates a "Response" class for each scraper engine.
25 It does this by parsing the "scraperFrame" to identify all the field names fetched by the scraper.
26 It defines a get/set method for each of these fields, each named the same as the field name found in the "scraperFrame".
27  
28 Optionally, you may write your own Response class and declare that as the Response class for your queries.
29 This is useful for defining a common Response class to a set of scraper engines (all auction sites, for instance).
30 See WWW::Scraper::Response::Auction for an example of this type of Response class.
31  
32 =head1 METHODS
33  
34 =over 8
35  
36 =item $fieldName
37  
38 As mentioned, Response will automatically define get/set methods for each of the fields in the "scraperFrame".
39 For instance, for a field named "postDate", you can get the field value with
40  
41 $response->postDate();
42  
43 You may also set the value of the postDate, but that would be kind of silly, wouldn't it?
44  
45 =item GetFieldNames
46  
47 A reference to a hash is returned listing all the field names in this response.
48 The keys of the hash are the field names, while the values are 1, 2, or 3.
49 A value of 1 means the value comes from the result page;
50 2 means the value comes from the detail page;
51 3 means the value is in both pages.
52  
53 =item SkipDetailPage
54  
55 A well-constructed Response class (as Scraper auto-generates) implements a lazy-access method for each
56 of the fields that come from the detail page.
57 This means the detail page is fetched only if you ask for that field value.
58 The SkipDetailPage() method controls whether the detail page will be fetched or not.
59 If you set it to 1, then the detail page is never fetched (detail dependent fields return undef).
60 Set to 2 to read the detail page on demand.
61 Set to 3 to read the detail page for fields that are only on the detail page,
62 and don't fetch the detail page, but return the results page value, for fields that appear on both pages.
63  
64 SkipDetailPage defaults to 2.
65  
66 =item ScrapeDetailPage
67  
68 Forces the detail page to be read and scraped right now.
69  
70 =item GetFieldValues
71  
72 Returns all field values of the response in a hash table (by reference).
73 Like GetFieldNames(), the keys are the field names, but in this case the values are the field values of each field.
74  
75 =item GetFieldTitles
76  
77 Returns a reference to a hash table containing titles for each field (which might be different than the field names).
78  
79 =back
80  
81 =head1 AUTHOR
82  
83 C<WWW::Scraper::Response::Scraper> is written and maintained
84 by Glenn Wood, http://search.cpan.org/search?mode=author&query=GLENNWOOD.
85  
86 =head1 COPYRIGHT
87  
88 Copyright (c) 2001 Glenn Wood
89 All rights reserved.
90  
91 This program is free software; you can redistribute it and/or
92 modify it under the same terms as Perl itself.
93  
94 =cut
95  
96 use strict;
97 use vars qw($VERSION @ISA);
98 @ISA = qw(WWW::SearchResult);
99 $VERSION = sprintf("%d.%02d", q$Revision: 1.13 $ =~ /(\d+)\.(\d+)/);
100 require WWW::SearchResult;
101 my (%AlreadyDeclared, $idCounter);
102  
103 print "WWW::Scraper::Response v$VERSION\n" if ( $WWW::Scraper::PRINT_VERSION );
104  
105 sub fieldCapture {
106 my ($scaffold) = @_;
107 my @fields = ();
108 my $next_scaffold;
109 SCAFFOLD: for my $scaffold ( @$scaffold ) {
110 $next_scaffold = undef;
111
112 my $tag = $$scaffold[0];
113 if ( ref($tag) ) {
114 push @fields, @{$tag->{'fieldsCaptured'}} if $tag->{'fieldsCaptured'};
115 my @scfld = @$scaffold;
116 $next_scaffold = $scfld[$#scfld] if ref($scfld[$#scfld]) eq 'ARRAY';
117 push @fields, fieldCapture($next_scaffold) if $next_scaffold;
118 }
119 elsif ( $tag =~ m/HIT|HIT\*/ )
120 {
121 my $resultType = $$scaffold[1];
122 if ( 'ARRAY' eq ref $resultType ) {
123 $next_scaffold = $resultType;
124 $resultType = '';
125 }
126 else
127 {
128 $resultType = "::$resultType";
129 $next_scaffold = $$scaffold[2];
130 }
131 }
132 elsif ( $tag =~ m/(HTML|TidyXML|TABLEX|TRX|DL|FOR)$/ )
133 {
134 my $i = 1;
135 while ( $$scaffold[$i] and 'ARRAY' ne ref($$scaffold[$i]) ) { $i += 1; }
136 $next_scaffold = $$scaffold[$i];
137 }
138 elsif ('BODYX' eq $tag) { # 'BODY', 'x', 'y' , [[.]]
139 if ( 'ARRAY' ne ref $$scaffold[3] ) # if next_scaffold is an array ref, then we'll recurse (below)
140 {
141 push @fields, $$scaffold[3];
142 next SCAFFOLD;
143 } else {
144 $next_scaffold = $$scaffold[3];
145 }
146 }
147 elsif ( 'DATA' eq $tag )
148 {
149 next SCAFFOLD unless ( $$scaffold[1] and $$scaffold[2] ) ;
150 push @fields, $$scaffold[3];
151 next SCAFFOLD;
152 }
153 elsif ( $tag =~ m/^(TABLEX|TRX|DL)$/ )
154 {
155 $next_scaffold = $$scaffold[1];
156 $next_scaffold = $$scaffold[2] unless ( 'ARRAY' eq ref $next_scaffold );
157 }
158 elsif ( 'TAG' eq $tag )
159 {
160 $next_scaffold = $$scaffold[2];
161 if ( 'ARRAY' ne ref $next_scaffold ) # if next_scaffold is an array ref, then we'll recurse (below)
162 {
163 push @fields, $next_scaffold if $next_scaffold;
164 next SCAFFOLD;
165 }
166 }
167 elsif ( $tag =~ m/^(TDX|DT|DD|DIV|SPAN|RESIDUE)$/ )
168 {
169 $next_scaffold = $$scaffold[1];
170 if ( 'ARRAY' ne ref $next_scaffold ) # if next_scaffold is an array ref, then we'll recurse (below)
171 {
172 push @fields, $next_scaffold if $next_scaffold;
173 next SCAFFOLD;
174 }
175 }
176 elsif ( 'AN' eq $tag )
177 {
178 #my $lbl = $$scaffold[1];
179 push @fields, $$scaffold[1] if $$scaffold[1];
180 push @fields, $$scaffold[2] if $$scaffold[2];
181 next SCAFFOLD;
182 }
183 elsif ( 'AQ' eq $tag )
184 {
185 #my $lbl = $$scaffold[1];
186 push @fields, $$scaffold[2] if $$scaffold[2];
187 push @fields, $$scaffold[3] if $$scaffold[3];
188 next SCAFFOLD;
189 }
190 elsif ( $tag =~ m{^(F|SNIP)$} ) # another idea: REGEX and F give their results to a sub-scraperFrame
191 { # instead of to a field - gdw.2003.01.16
192 my @ary = @$scaffold;
193 shift @ary;
194 shift @ary if (($tag eq 'SNIP') && $ary[0] && !ref($ary[0]));
195 map {
196 if ( 'ARRAY' eq ref($_) ) {
197 push @$next_scaffold, @$_;
198 } else {
199 push @fields, $_;
200 }
201 } @ary;
202 }
203 elsif ( 'CALLBACK' eq $tag )
204 {
205 my @ary = @$scaffold;
206 shift @ary; shift @ary; shift @ary; shift @ary;
207 $next_scaffold = shift @ary;
208 unless ( 'ARRAY' eq ref $next_scaffold ) {
209 push @fields, $next_scaffold if ( defined $next_scaffold );
210 next SCAFFOLD;
211 }
212 }
213 elsif ( $tag eq 'XPath' )
214 {
215 $next_scaffold = $$scaffold[2];
216 unless ( 'ARRAY' eq ref $next_scaffold ) {
217 push @fields, $next_scaffold if ( defined $next_scaffold );
218 next SCAFFOLD;
219 }
220 }
221 elsif ( $tag eq 'TRACE' )
222 {
223 next SCAFFOLD;
224 }
225 else {
226 die "Can't recognize Opcode '$tag' in scraper frame, from WWW::Scraper::Response::fieldCapture()";
227 }
228 push @fields, fieldCapture($next_scaffold) if $next_scaffold;
229 }
230 return @fields;
231 }
232  
233  
234 sub new {
235 my $SubClass = shift;
236 die "Scraper::Response::new() requires a subclass-name parameter." if !defined $SubClass || ref($SubClass);
237 $SubClass =~ s{^WWW\::Scraper\::Response\::}{};
238  
239 my $self;
240 my $scraperFrameCount = 0;
241 my $canonicalByResponseSubClassParameters = 0;
242 $SubClass = "::$SubClass";
243  
244 my (%subFields,$countSubFields);
245 unless ( $AlreadyDeclared{$SubClass} ) {
246
247 $subFields{'url'} = 1 if $SubClass eq '::Sherlock'; # Help Sherlock along.
248 $subFields{'detail'} = 1 if $SubClass eq '::Sherlock'; # Help Sherlock along.
249
250 while ( my $whatzit = shift ) {
251 if ( my $rf = ref $whatzit ) {
252 if ( 'HASH' eq $rf ) {
253 map { $subFields{$_} = $whatzit->{$_} || 1 } keys %$whatzit;
254 $canonicalByResponseSubClassParameters = 1;
255 }
256 elsif ( 'ARRAY' eq $rf ) {
257 $scraperFrameCount += 1;
258 map { $subFields{$_} = (defined $subFields{$_})?3:$scraperFrameCount if defined $_ } fieldCapture($whatzit);
259 }
260 else {
261 die "Invalid parameter to Scraper::Response: '$whatzit'";
262 }
263 }
264 }
265 delete $subFields{''}; # undef's in frame code's parameter lists are allowed, but should be ignored.
266  
267 my $subFieldsStruct = join '\'=>\'@\',\'__', keys %subFields;
268 die "No fields were found in the scraperFrames for WWW::Scraper::Response$SubClass\n" unless keys %subFields;
269  
270 my $type = $SubClass;
271 $type =~ s{^::}{};
272 my $typeLeaf = $type;
273 $typeLeaf =~ s{^.*:([^:]+)$}{$1};
274 my $baseClasses = '';
275 $baseClasses = "WWW::Scraper::Response::$1" if ( $type =~ m{^(.*)::[^:]+$} );
276 $baseClasses = "WWW::Scraper::Response$SubClass\::_struct_ $baseClasses WWW::Scraper::Response";
277 {
278 no warnings 'redefine';
279 eval <<EOT;
280 { package WWW::Scraper::Response$SubClass\::_struct_;
281 use Class::Struct;
282 struct ( 'WWW::Scraper::Response$SubClass\::_struct_' => {
283 '_state' => '\$'
284 ,'_searchObject' => '\$'
285 ,'_fieldCount' => '\$'
286 ,'_fieldNames' => '\$'
287 ,'_skipDetailPage' => '\$'
288 ,'_gotDetailPage' => '\$'
289 ,'_engines' => '\%'
290 ,'_native_query' => '\$'
291 ,'_native_options' => '\$' # reference to hash of native_options.
292 ,'_ScraperEngine' => '\$'
293 ,'_Scraper_debug' => '\$'
294 ,'_grubLevel' => '\$'
295 ,'_hitfound' => '\$'
296 ,'SubHitList' => '\$'
297 ,'SubHitList' => '\$'
298 # Now for the $SubClass specific members.
299 ,'__$subFieldsStruct'=>'\@'
300 }
301 );
302 }
303  
304 package WWW::Scraper::Response$SubClass;
305 use WWW::Scraper::Response;
306 use vars qw(\@ISA);
307 \@ISA = qw( $baseClasses );
308 sub new { bless new WWW::Scraper::Response$SubClass\::_struct_ }
309 sub type { return '$type' }
310 sub typeLeaf { return '$typeLeaf' }
311 1;
312 EOT
313 }
314 die $@ if $@;
315 $AlreadyDeclared{$SubClass} = [(keys %subFields)+11, \%subFields];
316
317 # Build 'wantarray' context sensitive accessors for all fields
318 # Build lazy-accessors for fields available from the Details page.
319 # my $fieldNames = ${AlreadyDeclared{$SubClass}}[1];
320
321 my $accessors = '';
322 for ( keys %subFields ) {
323 if ( $subFields{$_} == 1 ) {
324 $accessors .= <<EOT;
325 sub $_ {
326 my \$slf = shift;
327 my \$val = shift;
328 if ( defined \$val ) {
329 \$slf->_hitfound(1);
330 my \$ref = \$slf->__$_();
331 if ( defined \$ref ) {
332 push \@\$ref, \$val;
333 } else {
334 \$slf->__$_(1,\$val);
335 }
336 }
337 if ( wantarray ) {
338 return \@{\$slf->__$_()};
339 } else {
340 return \${\$slf->__$_()}[0];
341 }
342 }
343 EOT
344 }
345 if ( $subFields{$_} == 2 ) {
346 $accessors .= <<EOT;
347 sub $_ {
348 my \$slf = shift;
349 my \$val = shift;
350 \$slf->ScrapeDetailPage(\$slf->url());
351 if ( defined \$val ) {
352 \$slf->_hitfound(1);
353 my \$ref = \$slf->__$_();
354 if ( defined \$ref ) {
355 push \@\$ref, \$val;
356 } else {
357 \$slf->__$_(1,\$val);
358 }
359 }
360 if ( wantarray ) {
361 return \@{\$slf->__$_()};
362 } else {
363 return \${\$slf->__$_()}[0];
364 }
365 }
366 EOT
367 }
368 elsif ( $subFields{$_} == 3 ) {
369 $accessors .= <<EOT;
370 sub $_ {
371 my \$slf = shift;
372 my \$val = shift;
373 \$slf->ScrapeDetailPage(\$slf->url()) if defined(\$slf->_skipDetailPage()) && \$slf->_skipDetailPage() != 3;
374 if ( defined \$val ) {
375 \$slf->_hitfound(1);
376 my \$ref = \$slf->__$_();
377 if ( defined \$ref ) {
378 push \@\$ref, \$val;
379 } else {
380 \$slf->__$_(1,\$val);
381 }
382 }
383 if ( wantarray ) {
384 return \@{\$slf->__$_()};
385 } else {
386 return \${\$slf->__$_()}[0];
387 }
388 }
389 EOT
390 }
391 }
392  
393 my $warn = $^W;
394 $^W = 0; # Eliminates useless "warnings" during make test.
395 eval "{package WWW::Scraper::Response$SubClass; $accessors } 1";
396 $^W = $warn;
397 die $@ if $@;
398 }
399  
400 eval "\$self = new WWW::Scraper::Response$SubClass";
401
402 return $self;
403 }
404  
405 # private - friend of WWW::Scraper.
406 sub _AddToHitList {
407 my ($self,$hit) = @_;
408 my $subHitList = $self->SubHitList;
409 unless ( $subHitList ) {
410 $subHitList = [];
411 $self->SubHitList($subHitList);
412 }
413 push @$subHitList, $hit;
414 }
415  
416 sub plug_elem {
417 my ($self, $name, $value, $TidyXML) = @_;
418 return unless defined $name;
419 $value = [$value] unless ref($value) eq 'ARRAY';
420 $self->_elem($name, $$value[0]);
421 for ( @$value ) {
422 # sometimes this crashes cause $name is undefined.
423 # I don't know how it happens, but happened with ::CNN a lot. gdw.2002.09.09
424 eval { $self->$name(\$_); }; #die $@ if $@;
425 }
426 $self->_hitfound(1);
427 }
428 sub plug_url {
429 my ($self, $url) = @_;
430 $self->add_url($url);
431 $self->url(\$url);
432 $self->_hitfound(1);
433 }
434  
435  
436 # Return a table of names and origins for all data result columns.
437 sub GetFieldNames {
438 my $SubClass = ref(shift);
439 $SubClass =~ s{^WWW\::Scraper\::Response}{};
440 return $AlreadyDeclared{$SubClass}[1];
441 }
442  
443 # Return a table of names and titles for all data result columns.
444 sub GetFieldTitles {
445 my ($self) = @_;
446 my $answer = {'url' => 'URL'};
447 for ( keys %{$self->GetFieldNames} ) {
448 $answer->{$_} = $_ unless $_ =~ /^_/ or $_ =~ /^WWW::Search/;
449 }
450 return $answer;
451 }
452  
453  
454 sub GetFieldValues {
455 my $self = shift;
456 my $answer = {
457 # 'relevance' => $self->relevance()
458 'url' => scalar $self->url()
459 };
460 for ( keys %$self ) {
461 $answer->{$_} = $self->{$_} unless $_ =~ /^_/ or $_ eq 'url';
462 }
463 return $answer;
464 }
465  
466 # This gets the target document via HTTP GET, if needed.
467 sub response {
468 my ($self) = @_;
469  
470 my $request = HTTP::Request->new(GET => ${$self->url()});
471 $self->{'_response'} = $self->_searchObject()->{'user_agent'}->request($request);
472 return $self->{'_response'};
473 }
474  
475  
476 sub content {
477 my ($self) = @_;
478  
479 my $response = $self->response();
480 return $response->content() if $response->is_success;
481 return undef;
482 }
483  
484 # The default Response class "detail page" frame is null.
485 sub scraperDetail { undef }
486  
487 sub toString { shift->asString(@_) }
488 sub asString {
489 my ($self, $mod, $tabnum) = @_;
490 my $answer = '';
491  
492 $mod = 0 unless $mod; # Prevents useless diagnostics message.
493 $tabnum = 0 unless $tabnum; # Prevents useless diagnostics message.
494  
495 $answer .= " "x$tabnum."#--- ".ref($self)." ---#\n";
496 my %resultTitles = %{$self->GetFieldTitles()};# unless %resultTitles;
497 my %results = %{$self->GetFieldValues()};
498 # for ( keys %resultTitles ) {
499 my $fieldNames = $self->GetFieldNames();
500 for ( keys %$fieldNames ) {
501 if ( $mod == 0 ) {
502 my @value = $self->$_;
503 $answer .= " "x$tabnum."$resultTitles{$_}: (";
504 my $comma = '';
505 for ( @value ) {
506 #next unless defined $_ and defined $$_; #hmm. . . how does this happen, in eBay.
507 $answer .= "$comma'$$_'";# if $results{$_};
508 $comma = ', ';
509 }
510 $answer .= ")\n";
511 } else {
512 my $value = $self->$_;
513 # print "$resultTitles{$_}:= '$results{$_}'\n";# if $results{$_};
514 if ( defined $value ) {
515 $answer .= " "x$tabnum."$_: '$$value'\n";# if $results{$_};
516 } else {
517 $answer .= " "x$tabnum."$_: <NULL>\n";# if $results{$_};
518 }
519 }
520 }
521 if ( my $subHitList = $self->SubHitList ) {
522 for ( @$subHitList ) {
523 $answer .= $_->toString(0,$tabnum+1);
524 }
525 }
526 $answer .= "\n";
527 }
528  
529  
530 # Pairs in the $anchors hash are combined into <A> anchor tags.
531 sub toHTML { shift->asHtml(@_) }
532 sub asHtml {
533 my ($self, $anchors) = @_;
534 my $result = "<TABLE BORDER='4'>"; #<DT>from:</DT><DD>".$self->{'searchObject'}->scraperName()."</DD>\n";
535 my %results = %{$self->GetFieldValues()};
536 my %resultTitles = %{$self->GetFieldTitles()};
537
538 my $resultCount = 0;
539 my %missingResults = ();
540 for ( keys %resultTitles )
541 {
542 if ( $results{$_} ) {
543 $resultCount += 1 if $_ ne 'url' and $_ ne 'Description' and $_ ne 'Title';
544 } else {
545 $missingResults{$_} = 1;
546 }
547 }
548  
549 my $title = $self->title;
550 $title = $$title if ref($title);
551 my $url;
552 if ( $title eq 'Cached' or $title eq 'Similar pages' or
553 $title =~ m{^More results from } ) {
554 $url = $self->cachedURL();
555 $url = $$url if ref ($url);
556 } else {
557 $url = $results{'url'};
558 $url = $$url if ref($url);
559 }
560 $result .= "<TR><TD><B>$resultCount</B> fields";
561 if ( keys %missingResults ) {
562 my $comma = '';
563 $result .= '<BR>(';
564 for ( sort keys %missingResults ) {
565 $result .= $comma.$_;
566 $comma = ',';
567 }
568 $result .= ')';
569 }
570 $idCounter += 1;
571 $result .= "</TD><TD COLSPAN='2'>$resultTitles{'title'}: <A NAME='a_$idCounter' HREF='a_$idCounter' onclick='window.open(\"$url\",\"detailWindow\");detailWindow.focus()'>$title</A></TD></TR>\n";
572
573 $result .= "<TR><TD COLSPAN='3'>$resultTitles{'company'}: <A HREF='$results{'companyProfileURL'}'>$results{'company'}</A></TD></TR>\n"
574 if ($results{'companyProfileURL'});
575  
576 for my $title ( sort keys %resultTitles ) {
577 next if $title eq 'companyProfileURL' or $title eq 'company';
578 next if $title eq 'url' or $title eq 'title' or $title eq 'Description' or $title eq 'Title';
579 next unless $results{$title};
580 my @rslt = $self->$title;
581 shift @rslt unless $rslt[0];
582 $result .= "<TR><TD COLSPAN='1' valign='top'>$resultTitles{$title}</TD><TD COLSPAN='2'>";
583 my $comma = '';
584 for ( @rslt ) {
585 if ( $resultTitles{$title} =~ m{url}i ) {
586 $result .= "$comma<a href=\"$$_\">$$_</a>";
587 } else {
588 $result .= "$comma$$_";
589 }
590 $comma = "<BR>"
591 }
592 $result .= "</TD></TR>\n";
593 }
594 return $result.'</TABLE><BR>';
595 }
596  
597  
598 sub SkipDetailPage {
599 my $self = shift;
600 return $self->_skipDetailPage() if $_[0] < 1 or $_[0] > 3;
601 $self->_skipDetailPage(@_);
602 }
603  
604 # Fetch and scrape the detail page if necessary.
605 sub ScrapeDetailPage {
606 my ($self, $url) = @_;
607  
608 return unless $url;
609 return if defined($self->_skipDetailPage()) && $self->_skipDetailPage() == 1;
610
611 my $detail = $self->_gotDetailPage();
612 return if $detail;
613  
614 my $scraper = $self->_ScraperEngine();
615  
616 print STDERR 'DETAIL PAGE: '.$$url. "\n" if ($scraper->ScraperTrace('U'));
617  
618 eval {
619 # Why does http_request() cause Scraper::Brainpower to fail "Object Not Found" on next_url?
620 # this code from WWW::Search::http_request().
621 use HTTP::Request;
622 my $request = new HTTP::Request('GET', $$url);
623
624 if ($scraper->is_http_proxy_auth_data)
625 {
626 $request->proxy_authorization_basic($scraper->http_proxy_user,
627 $scraper->http_proxy_pwd);
628 }
629 $scraper->{'_cookie_jar'}->add_cookie_header($request) if ref($scraper->{'_cookie_jar'});
630
631 my $ua = $scraper->{'user_agent'};
632 my $response = $ua->request($request);
633 $detail = $response->content();
634 };
635 return if $@;
636
637 $self->_gotDetailPage($detail);
638 my $debug = '';
639 # Get scraper detail frame from the Response class, or the engine class if no Response frame.
640 my $scraperDetail = $self->scraperDetail?$self->scraperDetail:$scraper->scraperDetail();
641 $scraper->scrape($detail, $debug, $scraperDetail, $self);
642 }
643  
644 1;
645