1WWW::Search(3)        User Contributed Perl Documentation       WWW::Search(3)
2
3
4

NAME

6       WWW::Search - Virtual base class for WWW searches
7

SYNOPSIS

9         use WWW::Search;
10         my $sEngine = 'AltaVista';
11         my $oSearch = new WWW::Search($sEngine);
12

DESCRIPTION

14       This class is the parent for all access methods supported by the
15       "WWW::Search" library.  This library implements a Perl API to web-based
16       search engines.
17
18       See README for a list of search engines currently supported, and for a
19       lot of interesting high-level information about this distribution.
20
21       Search results can be limited, and there is a pause between each
22       request to avoid overloading either the client or the server.
23
24   Sample program
25       Here is a sample program:
26
27         my $sQuery = 'Columbus Ohio sushi restaurant';
28         my $oSearch = new WWW::Search('AltaVista');
29         $oSearch->native_query(WWW::Search::escape_query($sQuery));
30         $oSearch->login($sUser, $sPassword);
31         while (my $oResult = $oSearch->next_result())
32           {
33           print $oResult->url, "\n";
34           } # while
35         $oSearch->logout;
36
37       Results are objects of type "WWW::SearchResult" (see WWW::SearchResult
38       for details).  Note that different backends support different result
39       fields.  All backends are required to support title and url.
40

SEE ALSO

42       For specific search engines, see WWW::Search::TheEngineName (replacing
43       TheEngineName with a particular search engine).
44
45       For details about the results of a search, see WWW::SearchResult.
46

METHODS AND FUNCTIONS FOR SEARCHERS

48       new To create a new WWW::Search, call
49
50               $oSearch = new WWW::Search('SearchEngineName');
51
52           where SearchEngineName is replaced with a particular search engine.
53           For example:
54
55               $oSearch = new WWW::Search('Yahoo');
56
57           If no search engine is specified, a default (currently
58           'Null::Empty') will be chosen for you.
59
60       version
61           Returns the value of the $VERSION variable of the backend engine,
62           or $WWW::Search::VERSION if the backend does not contain $VERSION.
63
64       maintainer
65           Returns the value of the $MAINTAINER variable of the backend
66           engine, or $WWW::Search::MAINTAINER if the backend does not contain
67           $MAINTAINER.
68
69       installed_engines
70           Returns a list of the names of all installed backends.  We can not
71           tell if they are up-to-date or working, though.
72
73             use WWW::Search;
74             my @asEngines = sort &WWW::Search::installed_engines();
75             local $" = ', ';
76             print (" + These WWW::Search backends are installed: @asEngines\n");
77             # Choose a backend at random (yes, this is rather silly):
78             my $oSearch = WWW::Search->new($asEngines[rand(scalar(@asEngines))]);
79
80       native_query
81           Specify a query (and optional options) to the current search
82           object.  Previous query (if any) and its cached results (if any)
83           will be thrown away.  The option values and the query must be
84           escaped; call WWW::Search::escape_query() to escape a string.  The
85           search process is not actually begun until "results()" or
86           "next_result()" is called (lazy!), so native_query does not return
87           anything.
88
89           Example:
90
91             $oSearch->native_query('search-engine-specific+escaped+query+string',
92                                   { option1 => 'able', option2 => 'baker' } );
93
94           The hash of options following the query string is optional.  The
95           query string is backend-specific.  There are two kinds of options:
96           options specific to the backend, and generic options applicable to
97           multiple backends.
98
99           Generic options all begin with 'search_'.  Currently a few are
100           supported:
101
102           search_url
103               Specifies the base URL for the search engine.
104
105           search_debug
106               Enables backend debugging.  The default is 0 (no debugging).
107
108           search_parse_debug
109               Enables backend parser debugging.  The default is 0 (no
110               debugging).
111
112           search_to_file FILE
113               Causes the search results to be saved in a set of files
114               prefixed by FILE.  (Used internally by the test-suite, not
115               intended for general use.)
116
117           search_from_file FILE
118               Reads a search from a set of files prefixed by FILE.  (Used
119               internally by the test-suite, not intended for general use.)
120
121           Some backends may not implement these generic options, but any
122           which do implement them must provide these semantics.
123
124           Backend-specific options are described in the documentation for
125           each backend.  In most cases the options and their values are
126           packed together to create the query portion of the final URL.
127
128           Details about how the search string and option hash are interpreted
129           might be found in the search-engine-specific manual pages
130           (WWW::Search::SearchEngineName).
131
132       gui_query
133           Specify a query to the current search object; the query will be
134           performed with the engine's default options, as if it were typed by
135           a user in a browser window.
136
137           Same arguments as "native_query()" above.
138
139           Currently, this feature is supported by only a few backends;
140           consult the documentation for each backend to see if it is
141           implemented.
142
143       cookie_jar
144           Call this method (anytime before asking for results) if you want to
145           communicate cookie data with the search engine.  Takes one
146           argument, either a filename or an HTTP::Cookies object.  If you
147           give a filename, WWW::Search will attempt to read/store cookies
148           there (by passing the filename to HTTP::Cookies::new).
149
150             $oSearch->cookie_jar('/tmp/my_cookies');
151
152           If you give an HTTP::Cookies object, it is up to you to save the
153           cookies if/when you wish.
154
155             use HTTP::Cookies;
156             my $oJar = HTTP::Cookies->new(...);
157             $oSearch->cookie_jar($oJar);
158
159           If you pass in no arguments, the cookie jar (if any) is returned.
160
161             my $oJar = $oSearch->cookie_jar;
162             unless (ref $oJar) { print "No jar" };
163
164       date_from
165           Set/get the start date for limiting the query by a date range.  See
166           the documentation for each backend to find out if date ranges are
167           supported.
168
169       date_to
170           Set/get the end date for limiting the query by a date range.  See
171           the documentation for each backend to find out if date ranges are
172           supported.
173
174       env_proxy
175           Enable loading proxy settings from environment variables.  The
176           proxy URL will be read from $ENV{http_proxy}.  The username for
177           authentication will be read from $ENV{http_proxy_user}.  The
178           password for authentication will be read from $ENV{http_proxy_pwd}.
179
180           If you don't want to put passwords in the environment, one solution
181           would be to subclass LWP::UserAgent and use
182           $ENV{WWW_SEARCH_USERAGENT} instead (see user_agent below).
183
184           env_proxy() must be called before the first retrieval is attempted.
185
186           Example:
187
188             $ENV{http_proxy     } = 'http://my.proxy.com:80';
189             $ENV{http_proxy_user} = 'bugsbun';
190             $ENV{http_proxy_pwd } = 'c4rr0t5';
191             $oSearch->env_proxy('yes');  # Turn on with any true value
192             ...
193             $oSearch->env_proxy(0);  # Turn off with zero
194             ...
195             if ($oSearch->env_proxy)  # Test
196
197       http_proxy
198           Set up an HTTP proxy (for connections from behind a firewall).
199
200           Takes the same arguments as LWP::UserAgent::proxy().
201
202           This routine should be called before calling any of the result
203           functions (any method with "result" in its name).
204
205           Example:
206
207             # Turn on and set address:
208             $oSearch->http_proxy(['http','ftp'] => 'http://proxy:8080');
209             # Turn off:
210             $oSearch->http_proxy('');
211
212       http_proxy_user, http_proxy_pwd
213           Set/get HTTP proxy authentication data.
214
215           These routines set/get username and password used in proxy
216           authentication.  Authentication is attempted only if all three
217           items (proxy URL, username and password) have been set.
218
219           Example:
220
221               $oSearch->http_proxy_user("myuser");
222               $oSearch->http_proxy_pwd("mypassword");
223               $oSearch->http_proxy_user(undef);   # Example for no authentication
224
225               $username = $oSearch->http_proxy_user();
226
227       maximum_to_retrieve
228           Set the maximum number of hits to return.  Queries resulting in
229           more than this many hits will return the first hits, up to this
230           limit.  Although this specifies a maximum limit, search engines
231           might return less than this number.
232
233           Defaults to 500.
234
235           Example:
236               $max = $oSearch->maximum_to_retrieve(100);
237
238           You can also spell this method "maximum_to_return".
239
240       maximum_to_return
241           Synonym for maximum_to_retrieve
242
243       timeout
244           The maximum length of time any portion of the query should take, in
245           seconds.
246
247           Defaults to 60.
248
249           Example:
250               $oSearch->timeout(120);
251
252       login
253           Backends which need to login to the search engine should implement
254           this function.  Takes two arguments, user and password.  Return
255           nonzero if login was successful.  Return undef or 0 if login
256           failed.
257
258       logout
259           Backends which need to logout from the search engine should
260           implement this function.
261
262       approximate_result_count
263           Some backends indicate how many results they have found.  Typically
264           this is an approximate value.
265
266       approximate_hit_count
267           This is an alias for approximate_result_count().
268
269       results
270           Return all the results of a query as an array of WWW::SearchResult
271           objects.
272
273           Note: This might take a while, because a web backend will keep
274           asking the search engine for "next page of results" over and over
275           until there are no more next pages, and THEN return from this
276           function.
277
278           If an error occurs at any time during query processing, it will be
279           indicated in the response().
280
281           Example:
282
283               @results = $oSearch->results();
284               # Go have a cup of coffee while the previous line executes...
285               foreach $oResult (@results)
286                 {
287                 print $oResult->url(), "\n";
288                 } # foreach
289
290       next_result
291           Call this method repeatedly to return each result of a query as a
292           WWW::SearchResult object.  Example:
293
294               while ($oResult = $oSearch->next_result())
295                 {
296                 print $oResult->url(), "\n";
297                 } # while
298
299           When there are no more results, or if an error occurs,
300           next_result() will return undef.
301
302           If an error occurs at any time during query processing, it will be
303           indicated in the response().
304
305       seek_result($offset)
306           Set which result should be returned next time "next_result()" is
307           called.  Results are zero-indexed.
308
309           The only guaranteed valid offset is 0, which will replay the
310           results from the beginning.  In particular, seeking past the end of
311           the current cached results probably will not do what you might
312           think it should.
313
314           Results are cached, so this does not re-issue the query or cause IO
315           (unless you go off the end of the results).  To re-do the query,
316           create a new search object.
317
318           Example:
319
320               $oSearch->seek_result(0);
321
322       response
323           Returns an HTTP::Response object which resulted from the most-
324           recently-sent query.  Errors can be detected like this:
325
326               if (! $oSearch->response->is_success)
327                 {
328                 print STDERR "Error:  " . $oSearch->response->as_string() . "\n";
329                 } # if
330
331           Note to backend authors: even if the backend does not involve the
332           web, it should return an HTTP::Response object.
333
334       submit
335           This method can be used to submit URLs to the search engines for
336           indexing.  Consult the documentation for each backend to find out
337           if it is implemented there, and if so what the arguments are.
338
339           Returns an HTTP::Response object describing the result of the
340           submission request.  Consult the documentation for each backend to
341           find out the meaning of the response.
342
343       opaque
344           This function provides an application a place to store one opaque
345           data element (or many, via a Perl reference).  This facility is
346           useful to (for example), maintain client-specific information in
347           each active query when you have multiple concurrent queries.
348
349       escape_query
350           Escape a query.  Before queries are sent to the internet, special
351           characters must be escaped so that a proper URL can be formed.
352           This is like escaping a URL, but all non-alphanumeric characters
353           are escaped and and spaces are converted to "+"s.
354
355           Example:
356
357               $escaped = WWW::Search::escape_query('+hi +mom');
358               # $escaped is now '%2Bhi+%2Bmom'
359
360           See also "unescape_query()".  NOTE that this is not a method, it is
361           a plain function.
362
363       unescape_query
364           Unescape a query.  See "escape_query()" for details.
365
366           Example:
367
368               $unescaped = WWW::Search::unescape_query('%22hi+mom%22');
369               # $unescaped eq q{"hi mom"}
370
371           NOTE that this is not a method, it is a plain function.
372
373       strip_tags
374           Given a string, returns a copy of that string with HTML tags
375           removed.  This should be used by each backend as they insert the
376           title and description values into the search results objects.
377
378           NOTE that this is not a method, it is a plain function.
379
380       is_http_proxy
381           Returns true if proxy information is available.
382

METHODS AND FUNCTIONS FOR BACKEND PROGRAMMERS

384       reset_search
385           Resets internal data structures to start over with a new search (on
386           the same engine).
387
388       is_http_proxy_auth_data
389           Returns true if all authentication data (proxy URL, username, and
390           password) are available.
391
392       agent_name($sName)
393           If your search engine rejects certain browser, you can trick it
394           into thinking you're any browser type you want.  See below under
395           user_agent().
396
397       agent_email($sName)
398       user_agent($NON_ROBOT)
399           This internal routine creates a user-agent for derived classes that
400           query the web.  If any non-false argument is given, a normal
401           LWP::UserAgent (rather than a LWP::RobotUA) is used.
402
403           Returns the user-agent object.
404
405           If a backend needs the low-level LWP::UserAgent or LWP::RobotUA to
406           have a particular name, $oSearch->agent_name() and possibly
407           $oSearch->agent_email() should be called to set the desired values
408           *before* calling $oSearch->user_agent().
409
410           If the environment variable WWW_SEARCH_USERAGENT has a value, it
411           will be used as the class for a new user agent object.  This class
412           should be a subclass of LWP::UserAgent.  For example,
413
414             $ENV{WWW_SEARCH_USERAGENT} = 'My::Own::UserAgent';
415             # If this env.var. has no value,
416             # LWP::UserAgent or LWP::RobotUA will be used.
417             $oSearch = new WWW::Search('MyBackend');
418             $oSearch->agent_name('MySpider');
419             if ($iBackendWebsiteRequiresNonRobot)
420               {
421               $oSearch->user_agent('non-robot');
422               }
423             else
424               {
425               $oSearch->agent_email('me@here.com');
426               $oSearch->user_agent();
427               }
428
429           Backends should use robot-style user-agents whenever possible.
430
431       http_referer
432           Get / set the value of the HTTP_REFERER variable for this search
433           object.  Some search engines might only accept requests that
434           originated at some specific previous page.  This method lets
435           backend authors "fake" the previous page.  Call this method before
436           calling http_request.
437
438             $oSearch->http_referer('http://prev.engine.com/wherever/setup.html');
439             $oResponse = $oSearch->http_request('GET', $url);
440
441       http_method
442           Get / set the method to be used for the HTTP request.  Must be
443           either 'GET' or 'POST'.  Call this method before calling
444           http_request.  (Normally you would set this during
445           _native_setup_search().)  The default is 'GET'.
446
447             $oSearch->http_method('POST');
448
449       http_request($method, $url)
450           Submit the HTTP request to the world, and return the response.
451           Similar to LWP::UserAgent::request.  Handles cookies, follows
452           redirects, etc.  Requires that http_referer already be set up, if
453           needed.
454
455       next_url
456           Get or set the URL for the next backend request.  This can be used
457           to save the WWW::Search state between sessions (e.g. if you are
458           showing pages of results to the user in a web browser).  Before
459           closing down a session, save the value of next_url:
460
461             ...
462             $oSearch->maximum_to_return(10);
463             while ($oSearch->next_result) { ... }
464             my $urlSave = $oSearch->next_url;
465
466           Then, when you start up the next session (e.g. after the user
467           clicks your "next" button), restore this value before calling for
468           the results:
469
470             $oSearch->native_query(...);
471             $oSearch->next_url($urlSave);
472             $oSearch->maximum_to_return(20);
473             while ($oSearch->next_result) { ... }
474
475           WARNING: It is entirely up to you to keep your interface in sync
476           with the number of hits per page being returned from the backend.
477           And, we make no guarantees whether this method will work for any
478           given backend.  (Their caching scheme might not enable you to jump
479           into the middle of a list of search results, for example.)
480
481       split_lines
482           This internal routine splits data (typically the result of the web
483           page retrieval) into lines in a way that is OS independent.  If the
484           first argument is a reference to an array, that array is taken to
485           be a list of possible delimiters for this split.  For example,
486           Yahoo.pm uses <p> and <dd><li> as "line" delimiters for
487           convenience.
488
489       generic_option
490           This internal routine checks if an option is generic or backend
491           specific.  Currently all generic options begin with 'search_'.
492           This routine is not a method.
493
494       _native_setup_search
495           Do some backend-specific initialization.  It will be called with
496           the same arguments as native_query().
497
498       setup_search
499           This internal routine does generic Search setup.  It calls
500           "_native_setup_search()" to do backend-specific setup.
501
502       need_to_delay
503           A backend should override this method in order to dictate whether
504           user_agent_delay() needs to be called before the next HTTP request
505           is sent.  Return any perlish true or zero value.
506
507       user_agent_delay
508           According to what need_to_delay() returns, user_agent_delay() will
509           be called between requests to remote servers to avoid overloading
510           them with many back-to-back requests.
511
512       absurl
513           An internal routine to convert a relative URL into a absolute URL.
514           It takes two arguments, the 'base' url (usually the search engine
515           CGI URL) and the URL to be converted.  Returns a URI object.
516
517       retrieve_some
518           An internal routine to interface with "_native_retrieve_some()".
519           Checks for overflow.
520
521       _native_retrieve_some
522           Fetch the next page of results from the web engine, parse the
523           results, and prepare for the next page of results.
524
525           If a backend defines this method, it is in total control of the WWW
526           fetch, parsing, and preparing for the next page of results.  See
527           the WWW::Search::AltaVista module for example usage of the
528           _native_retrieve_some method.
529
530           An easier way to achieve this in a backend is to inherit
531           _native_retrieve_some from WWW::Search, and do only the HTML
532           parsing.  Simply define a method _parse_tree which takes one
533           argument, an HTML::TreeBuilder object, and returns an integer, the
534           number of results found on this page.  See the WWW::Search::Yahoo
535           module for example usage of the _parse_tree method.
536
537           A backend should, in general, define either _parse_tree() or
538           _native_retrieve_some(), but not both.
539
540           Additional features of the default _native_retrieve_some method:
541
542           Sets $self->{_prev_url} to the URL of the page just retrieved.
543
544           Calls $self->preprocess_results_page() on the raw HTML of the page.
545
546           Then, parses the page with an HTML::TreeBuilder object and passes
547           that populated object to $self->_parse_tree().
548
549           Additional notes on using the _parse_tree method:
550
551           The built-in HTML::TreeBuilder object used to parse the page has
552           store_comments turned ON.  If a backend needs to use a subclassed
553           or modified HTML::TreeBuilder object, the backend should set
554           $self->{'_treebuilder'} to that object before any results are
555           retrieved.  The best place to do this is at the end of
556           _native_setup_search.
557
558             my $oTree = new myTreeBuilder;
559             $oTree->store_pis(1);  # for example
560             $self->{'_treebuilder'} = $oTree;
561
562           When _parse_tree() is called, the $self->next_url is cleared.
563           During parsing, the backend should set $self->next_url to the
564           appropriate URL for the next page of results.  (If _parse_tree()
565           does not set the value, the search will end after parsing this page
566           of results.)
567
568           When _parse_tree() is called, the URL for the page being parsed can
569           be found in $self->{_prev_url}.
570
571       result_as_HTML
572           Given a WWW::SearchResult object, formats it human-readable with
573           HTML.
574
575       preprocess_results_page
576           A filter on the raw HTML of the results page.  This allows the
577           backend to alter the HTML before it is parsed, such as to correct
578           for known problems, HTML that can not be parsed correctly, etc.
579
580           Takes one argument, a string (the HTML webpage); returns one string
581           (the same HTML, modified).
582
583           This method is called from within _native_retrieve_some (above)
584           before the HTML of the page is parsed.
585
586           See the WWW::Search::Ebay distribution 2.07 or higher for example
587           usage.
588
589       test_cases (DEPRECATED)
590           Deprecated.
591
592           Returns the value of the $TEST_CASES variable of the backend
593           engine.
594
595       hash_to_cgi_string (DEPRECATED)
596           Given a reference to a hash of string => string, constructs a CGI
597           parameter string that looks like 'key1=value1&key2=value2'.
598
599           If the value is undef, the key will not be added to the string.
600
601           At one time, for testing purposes, we asked backends to use this
602           function rather than piecing the URL together by hand, to ensure
603           that URLs are identical across platforms and software versions.
604           But this is no longer necessary.
605
606           Example:
607
608               $self->{_options} = {
609                                    'opt3' => 'val3',
610                                    'search_url' => 'http://www.deja.com/dnquery.xp',
611                                    'opt1' => 'val1',
612                                    'QRY' => $native_query,
613                                    'opt2' => 'val2',
614                                   };
615               $self->{_next_url} = $self->{_options}{'search_url'} .'?'.
616                                    $self->hash_to_cgi_string($self->{_options});
617

IMPLEMENTING NEW BACKENDS

619       "WWW::Search" supports backends to separate search engines.  Each
620       backend is implemented as a subclass of "WWW::Search".
621       WWW::Search::Yahoo provides a good sample backend.
622
623       A backend must have the routine "_native_setup_search()".  A backend
624       must have the routine "_native_retrieve_some()" or "_parse_tree()".
625
626       "_native_setup_search()" is invoked before the search.  It is passed a
627       single argument: the escaped, native version of the query.
628
629       "_native_retrieve_some()" is the core of a backend.  It will be called
630       periodically to fetch URLs.  It should retrieve several hits from the
631       search service and add them to the cache.  It should return the number
632       of hits found, or undef when there are no more hits.
633
634       Internally, "_native_retrieve_some()" typically sends an HTTP request
635       to the search service, parses the HTML, extracts the links and
636       descriptions, then saves the URL for the next page of results.  See the
637       code for the "WWW::Search::AltaVista" module for an example.
638
639       Alternatively, a backend can define the method "_parse_tree()" instead
640       of "_native_retrieve_some()".  See the "WWW::Search::Ebay" module for a
641       good example.
642
643       If you implement a new backend, please let the authors know.
644

BUGS AND DESIRED FEATURES

646       The bugs are there for you to find (some people call them Easter Eggs).
647
648       Desired features:
649
650       A portable query language.
651           A portable language would easily allow you to move queries easily
652           between different search engines.  A query abstraction is non-
653           trivial and unfortunately will not be done any time soon by the
654           current maintainer.  If you want to take a shot at it, please let
655           me know.
656

AUTHOR

658       John Heidemann <johnh@isi.edu> Maintained by Martin Thurn,
659       "mthurn@cpan.org", <http://www.sandcrawler.com/SWB/cpan-modules.html>.
660
662       Copyright (c) 1996 University of Southern California.  All rights
663       reserved.
664
665       Redistribution and use in source and binary forms are permitted
666       provided that the above copyright notice and this paragraph are
667       duplicated in all such forms and that any documentation, advertising
668       materials, and other materials related to such distribution and use
669       acknowledge that the software was developed by the University of
670       Southern California, Information Sciences Institute.  The name of the
671       University may not be used to endorse or promote products derived from
672       this software without specific prior written permission.
673
674       THIS SOFTWARE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED
675       WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
676       MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
677
678
679
680perl v5.30.0                      2019-07-26                    WWW::Search(3)
Impressum