{
    "mode": "perldoc",
    "parameter": "WWW::Search",
    "section": "",
    "url": "https://www.chedong.com/phpMan.php/perldoc/WWW%3A%3ASearch/json",
    "generated": "2026-06-12T06:59:53Z",
    "synopsis": "use WWW::Search;\nmy $sEngine = 'AltaVista';\nmy $oSearch = new WWW::Search($sEngine);",
    "sections": {
        "NAME": {
            "content": "WWW::Search - Virtual base class for WWW searches\n",
            "subsections": []
        },
        "SYNOPSIS": {
            "content": "use WWW::Search;\nmy $sEngine = 'AltaVista';\nmy $oSearch = new WWW::Search($sEngine);\n",
            "subsections": []
        },
        "DESCRIPTION": {
            "content": "This class is the parent for all access methods supported by the \"WWW::Search\" library. This\nlibrary implements a Perl API to web-based search engines.\n\nSee README for a list of search engines currently supported, and for a lot of interesting\nhigh-level information about this distribution.\n\nSearch results can be limited, and there is a pause between each request to avoid overloading\neither the client or the server.\n",
            "subsections": [
                {
                    "name": "Sample program",
                    "content": "Here is a sample program:\n\nmy $sQuery = 'Columbus Ohio sushi restaurant';\nmy $oSearch = new WWW::Search('AltaVista');\n$oSearch->nativequery(WWW::Search::escapequery($sQuery));\n$oSearch->login($sUser, $sPassword);\nwhile (my $oResult = $oSearch->nextresult())\n{\nprint $oResult->url, \"\\n\";\n} # while\n$oSearch->logout;\n\nResults are objects of type \"WWW::SearchResult\" (see WWW::SearchResult for details). Note that\ndifferent backends support different result fields. All backends are required to support title\nand url.\n"
                }
            ]
        },
        "SEE ALSO": {
            "content": "For specific search engines, see WWW::Search::TheEngineName (replacing TheEngineName with a\nparticular search engine).\n\nFor details about the results of a search, see WWW::SearchResult.\n",
            "subsections": []
        },
        "METHODS AND FUNCTIONS FOR SEARCHERS": {
            "content": "new To create a new WWW::Search, call\n\n$oSearch = new WWW::Search('SearchEngineName');\n\nwhere SearchEngineName is replaced with a particular search engine. For example:\n\n$oSearch = new WWW::Search('Yahoo');\n\nIf no search engine is specified, a default (currently 'Null::Empty') will be chosen for\nyou.\n\nversion\nReturns the value of the $VERSION variable of the backend engine, or $WWW::Search::VERSION\nif the backend does not contain $VERSION.\n\nmaintainer\nReturns the value of the $MAINTAINER variable of the backend engine, or\n$WWW::Search::MAINTAINER if the backend does not contain $MAINTAINER.\n\ninstalledengines\nReturns a list of the names of all installed backends. We can not tell if they are\nup-to-date or working, though.\n\nuse WWW::Search;\nmy @asEngines = sort &WWW::Search::installedengines();\nlocal $\" = ', ';\nprint (\" + These WWW::Search backends are installed: @asEngines\\n\");\n# Choose a backend at random (yes, this is rather silly):\nmy $oSearch = WWW::Search->new($asEngines[rand(scalar(@asEngines))]);\n\nnativequery\nSpecify a query (and optional options) to the current search object. Previous query (if any)\nand its cached results (if any) will be thrown away. The option values and the query must be\nescaped; call WWW::Search::escapequery() to escape a string. The search process is not\nactually begun until \"results()\" or \"nextresult()\" is called (lazy!), so nativequery does\nnot return anything.\n\nExample:\n\n$oSearch->nativequery('search-engine-specific+escaped+query+string',\n{ option1 => 'able', option2 => 'baker' } );\n\nThe hash of options following the query string is optional. The query string is\nbackend-specific. There are two kinds of options: options specific to the backend, and\ngeneric options applicable to multiple backends.\n\nGeneric options all begin with 'search'. Currently a few are supported:\n\nsearchurl\nSpecifies the base URL for the search engine.\n\nsearchdebug\nEnables backend debugging. The default is 0 (no debugging).\n\nsearchparsedebug\nEnables backend parser debugging. The default is 0 (no debugging).\n\nsearchtofile FILE\nCauses the search results to be saved in a set of files prefixed by FILE. (Used\ninternally by the test-suite, not intended for general use.)\n\nsearchfromfile FILE\nReads a search from a set of files prefixed by FILE. (Used internally by the test-suite,\nnot intended for general use.)\n\nSome backends may not implement these generic options, but any which do implement them must\nprovide these semantics.\n\nBackend-specific options are described in the documentation for each backend. In most cases\nthe options and their values are packed together to create the query portion of the final\nURL.\n\nDetails about how the search string and option hash are interpreted might be found in the\nsearch-engine-specific manual pages (WWW::Search::SearchEngineName).\n\nguiquery\nSpecify a query to the current search object; the query will be performed with the engine's\ndefault options, as if it were typed by a user in a browser window.\n\nSame arguments as \"nativequery()\" above.\n\nCurrently, this feature is supported by only a few backends; consult the documentation for\neach backend to see if it is implemented.\n\ncookiejar\nCall this method (anytime before asking for results) if you want to communicate cookie data\nwith the search engine. Takes one argument, either a filename or an HTTP::Cookies object. If\nyou give a filename, WWW::Search will attempt to read/store cookies there (by passing the\nfilename to HTTP::Cookies::new).\n\n$oSearch->cookiejar('/tmp/mycookies');\n\nIf you give an HTTP::Cookies object, it is up to you to save the cookies if/when you wish.\n\nuse HTTP::Cookies;\nmy $oJar = HTTP::Cookies->new(...);\n$oSearch->cookiejar($oJar);\n\nIf you pass in no arguments, the cookie jar (if any) is returned.\n\nmy $oJar = $oSearch->cookiejar;\nunless (ref $oJar) { print \"No jar\" };\n\ndatefrom\nSet/get the start date for limiting the query by a date range. See the documentation for\neach backend to find out if date ranges are supported.\n\ndateto\nSet/get the end date for limiting the query by a date range. See the documentation for each\nbackend to find out if date ranges are supported.\n\nenvproxy\nEnable loading proxy settings from environment variables. The proxy URL will be read from\n$ENV{httpproxy}. The username for authentication will be read from $ENV{httpproxyuser}.\nThe password for authentication will be read from $ENV{httpproxypwd}.\n\nIf you don't want to put passwords in the environment, one solution would be to subclass\nLWP::UserAgent and use $ENV{WWWSEARCHUSERAGENT} instead (see useragent below).\n\nenvproxy() must be called before the first retrieval is attempted.\n\nExample:\n\n$ENV{httpproxy     } = 'http://my.proxy.com:80';\n$ENV{httpproxyuser} = 'bugsbun';\n$ENV{httpproxypwd } = 'c4rr0t5';\n$oSearch->envproxy('yes');  # Turn on with any true value\n...\n$oSearch->envproxy(0);  # Turn off with zero\n...\nif ($oSearch->envproxy)  # Test\n\nhttpproxy\nSet up an HTTP proxy (for connections from behind a firewall).\n\nTakes the same arguments as LWP::UserAgent::proxy().\n\nThis routine should be called before calling any of the result functions (any method with\n\"result\" in its name).\n\nExample:\n\n# Turn on and set address:\n$oSearch->httpproxy(['http','ftp'] => 'http://proxy:8080');\n# Turn off:\n$oSearch->httpproxy('');\n\nhttpproxyuser, httpproxypwd\nSet/get HTTP proxy authentication data.\n\nThese routines set/get username and password used in proxy authentication. Authentication is\nattempted only if all three items (proxy URL, username and password) have been set.\n\nExample:\n\n$oSearch->httpproxyuser(\"myuser\");\n$oSearch->httpproxypwd(\"mypassword\");\n$oSearch->httpproxyuser(undef);   # Example for no authentication\n\n$username = $oSearch->httpproxyuser();\n\nmaximumtoretrieve\nSet the maximum number of hits to return. Queries resulting in more than this many hits will\nreturn the first hits, up to this limit. Although this specifies a maximum limit, search\nengines might return less than this number.\n\nDefaults to 500.\n\nExample: $max = $oSearch->maximumtoretrieve(100);\n\nYou can also spell this method \"maximumtoreturn\".\n\nmaximumtoreturn\nSynonym for maximumtoretrieve\n\ntimeout\nThe maximum length of time any portion of the query should take, in seconds.\n\nDefaults to 60.\n\nExample: $oSearch->timeout(120);\n\nlogin\nBackends which need to login to the search engine should implement this function. Takes two\narguments, user and password. Return nonzero if login was successful. Return undef or 0 if\nlogin failed.\n\nlogout\nBackends which need to logout from the search engine should implement this function.\n\napproximateresultcount\nSome backends indicate how many results they have found, e.g. with a number shown at the top\nof the search results page. Note that there is no corresponding method that returns the\nactual count of results; that's because results are normally retrieved in batches (i.e.\npages) and at any given time there's no way to know how big the final list of results will\nbe. NEW: if request has not been made to the search provider, this method will return undef\n(used to return zero). NEW: if the results page does not explicitly indicate the result\ncount, this method will return undef (used to return zero).\n\napproximatehitcount\nThis is an alias for approximateresultcount().\n\nresults\nReturn all the results of a query as an array of WWW::SearchResult objects.\n\nNote: This might take a while, because a web backend will keep asking the search engine for\n\"next page of results\" over and over until there are no more next pages, and THEN return\nfrom this function.\n\nIf an error occurs at any time during query processing, it will be indicated in the\nresponse().\n\nExample:\n\n@results = $oSearch->results();\n# Go have a cup of coffee while the previous line executes...\nforeach $oResult (@results)\n{\nprint $oResult->url(), \"\\n\";\n} # foreach\n\nnextresult\nCall this method repeatedly to return each result of a query as a WWW::SearchResult object.\nExample:\n\nwhile ($oResult = $oSearch->nextresult())\n{\nprint $oResult->url(), \"\\n\";\n} # while\n\nWhen there are no more results, or if an error occurs, nextresult() will return undef.\n\nIf an error occurs at any time during query processing, it will be indicated in the\nresponse().\n",
            "subsections": [
                {
                    "name": "seek_result",
                    "content": "Set which result should be returned next time \"nextresult()\" is called. Results are\nzero-indexed.\n\nThe only guaranteed valid offset is 0, which will replay the results from the beginning. In\nparticular, seeking past the end of the current cached results probably will not do what you\nmight think it should.\n\nResults are cached, so this does not re-issue the query or cause IO (unless you go off the\nend of the results). To re-do the query, create a new search object.\n\nExample:\n\n$oSearch->seekresult(0);\n\nresponse\nReturns an HTTP::Response object which resulted from the most-recently-sent query. Errors\ncan be detected like this:\n\nif (! $oSearch->response->issuccess)\n{\nprint STDERR \"Error:  \" . $oSearch->response->asstring() . \"\\n\";\n} # if\n\nNote to backend authors: even if the backend does not involve the web, it should return an\nHTTP::Response object.\n\nsubmit\nThis method can be used to submit URLs to the search engines for indexing. Consult the\ndocumentation for each backend to find out if it is implemented there, and if so what the\narguments are.\n\nReturns an HTTP::Response object describing the result of the submission request. Consult\nthe documentation for each backend to find out the meaning of the response.\n\nopaque\nThis function provides an application a place to store one opaque data element (or many, via\na Perl reference). This facility is useful to (for example), maintain client-specific\ninformation in each active query when you have multiple concurrent queries.\n\nescapequery\nEscape a query. Before queries are sent to the internet, special characters must be escaped\nso that a proper URL can be formed. This is like escaping a URL, but all non-alphanumeric\ncharacters are escaped and and spaces are converted to \"+\"s.\n\nExample:\n\n$escaped = WWW::Search::escapequery('+hi +mom');\n# $escaped is now '%2Bhi+%2Bmom'\n\nSee also \"unescapequery()\". NOTE that this is not a method, it is a plain function.\n\nunescapequery\nUnescape a query. See \"escapequery()\" for details.\n\nExample:\n\n$unescaped = WWW::Search::unescapequery('%22hi+mom%22');\n# $unescaped eq q{\"hi mom\"}\n\nNOTE that this is not a method, it is a plain function.\n\nstriptags\nGiven a string, returns a copy of that string with HTML tags removed. This should be used by\neach backend as they insert the title and description values into the search results\nobjects.\n\nNOTE that this is not a method, it is a plain function.\n\nishttpproxy\nReturns true if proxy information is available.\n"
                }
            ]
        },
        "METHODS AND FUNCTIONS FOR BACKEND PROGRAMMERS": {
            "content": "resetsearch\nResets internal data structures to start over with a new search (on the same engine).\n\nishttpproxyauthdata\nReturns true if all authentication data (proxy URL, username, and password) are available.\n",
            "subsections": [
                {
                    "name": "agent_name",
                    "content": "If your search engine rejects certain browser, you can trick it into thinking you're any\nbrowser type you want. See below under useragent().\n"
                },
                {
                    "name": "agent_email",
                    "content": ""
                },
                {
                    "name": "user_agent",
                    "content": "This internal routine creates a user-agent for derived classes that query the web. If any\nnon-false argument is given, a normal LWP::UserAgent (rather than a LWP::RobotUA) is used.\n\nReturns the user-agent object.\n\nIf a backend needs the low-level LWP::UserAgent or LWP::RobotUA to have a particular name,\n$oSearch->agentname() and possibly $oSearch->agentemail() should be called to set the\ndesired values *before* calling $oSearch->useragent().\n\nIf the environment variable WWWSEARCHUSERAGENT has a value, it will be used as the class\nfor a new user agent object. This class should be a subclass of LWP::UserAgent. For example,\n\n$ENV{WWWSEARCHUSERAGENT} = 'My::Own::UserAgent';\n# If this env.var. has no value,\n# LWP::UserAgent or LWP::RobotUA will be used.\n$oSearch = new WWW::Search('MyBackend');\n$oSearch->agentname('MySpider');\nif ($iBackendWebsiteRequiresNonRobot)\n{\n$oSearch->useragent('non-robot');\n}\nelse\n{\n$oSearch->agentemail('me@here.com');\n$oSearch->useragent();\n}\n\nBackends should use robot-style user-agents whenever possible.\n\nhttpreferer\nGet / set the value of the HTTPREFERER variable for this search object. Some search engines\nmight only accept requests that originated at some specific previous page. This method lets\nbackend authors \"fake\" the previous page. Call this method before calling httprequest.\n\n$oSearch->httpreferer('http://prev.engine.com/wherever/setup.html');\n$oResponse = $oSearch->httprequest('GET', $url);\n\nhttpmethod\nGet / set the method to be used for the HTTP request. Must be either 'GET' or 'POST'. Call\nthis method before calling httprequest. (Normally you would set this during\nnativesetupsearch().) The default is 'GET'.\n\n$oSearch->httpmethod('POST');\n"
                },
                {
                    "name": "http_request",
                    "content": "Submit the HTTP request to the world, and return the response. Similar to\nLWP::UserAgent::request. Handles cookies, follows redirects, etc. Requires that httpreferer\nalready be set up, if needed.\n\nnexturl\nGet or set the URL for the next backend request. This can be used to save the WWW::Search\nstate between sessions (e.g. if you are showing pages of results to the user in a web\nbrowser). Before closing down a session, save the value of nexturl:\n\n...\n$oSearch->maximumtoreturn(10);\nwhile ($oSearch->nextresult) { ... }\nmy $urlSave = $oSearch->nexturl;\n\nThen, when you start up the next session (e.g. after the user clicks your \"next\" button),\nrestore this value before calling for the results:\n\n$oSearch->nativequery(...);\n$oSearch->nexturl($urlSave);\n$oSearch->maximumtoreturn(20);\nwhile ($oSearch->nextresult) { ... }\n\nWARNING: It is entirely up to you to keep your interface in sync with the number of hits per\npage being returned from the backend. And, we make no guarantees whether this method will\nwork for any given backend. (Their caching scheme might not enable you to jump into the\nmiddle of a list of search results, for example.)\n\nsplitlines\nThis internal routine splits data (typically the result of the web page retrieval) into\nlines in a way that is OS independent. If the first argument is a reference to an array,\nthat array is taken to be a list of possible delimiters for this split. For example,\nYahoo.pm uses <p> and <dd><li> as \"line\" delimiters for convenience.\n\ngenericoption\nThis internal routine checks if an option is generic or backend specific. Currently all\ngeneric options begin with 'search'. This routine is not a method.\n\nnativesetupsearch\nDo some backend-specific initialization. It will be called with the same arguments as\nnativequery().\n\nsetupsearch\nThis internal routine does generic Search setup. It calls \"nativesetupsearch()\" to do\nbackend-specific setup.\n\nneedtodelay\nA backend should override this method in order to dictate whether useragentdelay() needs\nto be called before the next HTTP request is sent. Return any perlish true or zero value.\n\nuseragentdelay\nAccording to what needtodelay() returns, useragentdelay() will be called between\nrequests to remote servers to avoid overloading them with many back-to-back requests.\n\nabsurl\nAn internal routine to convert a relative URL into a absolute URL. It takes two arguments,\nthe 'base' url (usually the search engine CGI URL) and the URL to be converted. Returns a\nURI object.\n\nretrievesome\nAn internal routine to interface with \"nativeretrievesome()\". Checks for overflow.\n\nnativeretrievesome\nFetch the next page of results from the web engine, parse the results, and prepare for the\nnext page of results.\n\nIf a backend defines this method, it is in total control of the WWW fetch, parsing, and\npreparing for the next page of results. See the WWW::Search::AltaVista module for example\nusage of the nativeretrievesome method.\n\nAn easier way to achieve this in a backend is to inherit nativeretrievesome from\nWWW::Search, and do only the HTML parsing. Simply define a method parsetree which takes\none argument, an HTML::TreeBuilder object, and returns an integer, the number of results\nfound on this page. See the WWW::Search::Yahoo module for example usage of the parsetree\nmethod.\n\nA backend should, in general, define either parsetree() or nativeretrievesome(), but\nnot both.\n\nAdditional features of the default nativeretrievesome method:\n\nSets $self->{prevurl} to the URL of the page just retrieved.\n\nCalls $self->preprocessresultspage() on the raw HTML of the page.\n\nThen, parses the page with an HTML::TreeBuilder object and passes that populated object to\n$self->parsetree().\n\nAdditional notes on using the parsetree method:\n\nThe built-in HTML::TreeBuilder object used to parse the page has storecomments turned ON.\nIf a backend needs to use a subclassed or modified HTML::TreeBuilder object, the backend\nshould set $self->{'treebuilder'} to that object before any results are retrieved. The best\nplace to do this is at the end of nativesetupsearch.\n\nmy $oTree = new myTreeBuilder;\n$oTree->storepis(1);  # for example\n$self->{'treebuilder'} = $oTree;\n\nWhen parsetree() is called, the $self->nexturl is cleared. During parsing, the backend\nshould set $self->nexturl to the appropriate URL for the next page of results. (If\nparsetree() does not set the value, the search will end after parsing this page of\nresults.)\n\nWhen parsetree() is called, the URL for the page being parsed can be found in\n$self->{prevurl}.\n\nresultasHTML\nGiven a WWW::SearchResult object, formats it human-readable with HTML.\n\npreprocessresultspage\nA filter on the raw HTML of the results page. This allows the backend to alter the HTML\nbefore it is parsed, such as to correct for known problems, HTML that can not be parsed\ncorrectly, etc.\n\nTakes one argument, a string (the HTML webpage); returns one string (the same HTML,\nmodified).\n\nThis method is called from within nativeretrievesome (above) before the HTML of the page\nis parsed.\n\nSee the WWW::Search::Ebay distribution 2.07 or higher for example usage.\n\ntestcases (DEPRECATED)\nDeprecated.\n\nReturns the value of the $TESTCASES variable of the backend engine.\n\nhashtocgistring (DEPRECATED)\nGiven a reference to a hash of string => string, constructs a CGI parameter string that\nlooks like 'key1=value1&key2=value2'.\n\nIf the value is undef, the key will not be added to the string.\n\nAt one time, for testing purposes, we asked backends to use this function rather than\npiecing the URL together by hand, to ensure that URLs are identical across platforms and\nsoftware versions. But this is no longer necessary.\n\nExample:\n\n$self->{options} = {\n'opt3' => 'val3',\n'searchurl' => 'http://www.deja.com/dnquery.xp',\n'opt1' => 'val1',\n'QRY' => $nativequery,\n'opt2' => 'val2',\n};\n$self->{nexturl} = $self->{options}{'searchurl'} .'?'.\n$self->hashtocgistring($self->{options});\n"
                }
            ]
        },
        "IMPLEMENTING NEW BACKENDS": {
            "content": "\"WWW::Search\" supports backends to separate search engines. Each backend is implemented as a\nsubclass of \"WWW::Search\". WWW::Search::Yahoo provides a good sample backend.\n\nA backend must have the routine \"nativesetupsearch()\". A backend must have the routine\n\"nativeretrievesome()\" or \"parsetree()\".\n\n\"nativesetupsearch()\" is invoked before the search. It is passed a single argument: the\nescaped, native version of the query.\n\n\"nativeretrievesome()\" is the core of a backend. It will be called periodically to fetch\nURLs. It should retrieve several hits from the search service and add them to the cache. It\nshould return the number of hits found, or undef when there are no more hits.\n\nInternally, \"nativeretrievesome()\" typically sends an HTTP request to the search service,\nparses the HTML, extracts the links and descriptions, then saves the URL for the next page of\nresults. See the code for the \"WWW::Search::AltaVista\" module for an example.\n\nAlternatively, a backend can define the method \"parsetree()\" instead of\n\"nativeretrievesome()\". See the \"WWW::Search::Ebay\" module for a good example.\n\nIf you implement a new backend, please let the authors know.\n",
            "subsections": []
        },
        "BUGS AND DESIRED FEATURES": {
            "content": "The bugs are there for you to find (some people call them Easter Eggs).\n\nDesired features:\n\nA portable query language.\nA portable language would easily allow you to move queries easily between different search\nengines. A query abstraction is non-trivial and unfortunately will not be done any time soon\nby the current maintainer. If you want to take a shot at it, please let me know.\n",
            "subsections": []
        },
        "AUTHOR": {
            "content": "John Heidemann <johnh@isi.edu> Maintained by Martin Thurn, \"mthurn@cpan.org\",\n<http://www.sandcrawler.com/SWB/cpan-modules.html>.\n",
            "subsections": []
        },
        "COPYRIGHT": {
            "content": "Copyright (c) 1996 University of Southern California. All rights reserved.\n\nRedistribution and use in source and binary forms are permitted provided that the above\ncopyright notice and this paragraph are duplicated in all such forms and that any documentation,\nadvertising materials, and other materials related to such distribution and use acknowledge that\nthe software was developed by the University of Southern California, Information Sciences\nInstitute. The name of the University may not be used to endorse or promote products derived\nfrom this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED \"AS IS\" AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,\nWITHOUT LIMITATION, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\nPURPOSE.\n",
            "subsections": []
        }
    },
    "summary": "WWW::Search - Virtual base class for WWW searches",
    "flags": [],
    "examples": [],
    "see_also": []
}