Google and Perl
The Perl Journal May 2003
By brian d foy
brian is the founder of the first Perl Users Group, NY.pm, and Perl Mongers, the Perl advocacy organization. He has been teaching Perl through Stonehenge Consulting for the past five years, and can be contacted at [email protected].
Google has become the most popular search engine for techies, even to the extent that a lot of people have been treating Google as just another part of their application. In response, Google set up a SOAP service to allow people to access their services and get a response in XML. At the moment, the program is an experimental beta service and Google limits the number of SOAP queries to 1000 per developer, which is about one query every minute and a half.
To use the Google Web API, I need to register as a developer and get a developer's token at http://www.google.com/apis/. This leads me through the sign up process and provides links to documentation and FAQs. The developer's kit comes with a Web Services Description Language (WSDL) file that I can use with SOAP::Lite to set up the service and insulate me from the specifics of the SOAP stuff going on. I just want to get my search results.
The process is simple: I load the SOAP::Lite module and use its service method to create my search object, $search. The argument to service is the location of the WSDL file, which I have in the same directory as the script. I store my Google Developer's Key in my shell's environment and access it as $ENV{GOOGLE_KEY}. I print the results with Data::Dumper because it is quick and easy. Later, I will use the Google API to access the information.
Making a Query
The doGoogleSearch() method comes from the WSDL file and takes several arguments. If I leave off any of the arguments, the search fails.
Developer's key Query terms Starting search result Maximum search results (10 the highest)
...and some others the API describes and I do not use.
#!/usr/bin/perl use strict; use Data::Dumper; use SOAP::Lite; my $search = SOAP::Lite->service("File:search.wsdl"); my $results = $search->doGoogleSearch( $ENV{GOOGLE_KEY}, 'TPJ', 0, 10, "false", "", "false", "", "latin1", "latin1"); print Data::Dumper::Dumper( $results );
When I first ran this program, the initial search result I got had the title "TPJ Sues State Lawmaker Over Open Records," and "The Perl Journal" was the second search result. The other TPJ is Texans for Public Justice. The third argument to doGoogleSearch(), the results index, is zero based just like Perl, and I had used "1." Further down in the list, I found another TPJ magazine, the Tube & Pipe Journal (http://www.fmametalfab.org/croydon2k/ tubepipe.htm), in case you can't get enough TPJ.
Manipulating the Results
The return value is a Perl data structure, and since I already dumped it with Data::Dumper, I know what it looks like. It is an anonymous hash that has keys that describe the search, including the arguments to doGoogleSearch(), and how long it took to do the search. Some modules on CPAN, such as Net::Google, provide object access to this structure, but I find it just as easy to play with the data structure.
The search results are in the resultsElements key, and each result is another anonymous hash.
$VAR1 = bless( { 'endIndex' => '1', 'searchTime' => '0.11542', 'searchComments' => '', 'documentFiltering' => 0, 'searchQuery' => 'TPJ', 'estimatedTotalResultsCount' => '48400', 'searchTips' => '', 'startIndex' => '1', 'resultElements' => [ bless( { 'URL' => 'http://www.tpj.com/', 'snippet' => ' <b>...</b> <b>TPJ</b> was published as a standalone quarterly magazine until 2001 when<br> it became a quarterly supplement to Sys Admin magazine. Beginning <b>...</b> ', 'directoryTitle' => 'The Perl Journal', 'hostName' => '', 'relatedInformationPresent' => 1, 'directoryCategory' => bless( { 'fullViewableName' => 'Top/Computers/Programming/Languages/Perl/Magazines_and_E-zines', 'specialEncoding' => '' }, 'DirectoryCategory' ), 'summary' => 'The first and only periodical devoted to Perl.', 'cachedSize' => '12k', 'title' => 'The Perl Journal' }, 'ResultElement' ) ], 'directoryCategories' => [], 'estimateIsExact' => 0 }, 'searchResult' );
I want to print the title and the link of the results. I modify my earlier program to extract the resultElements portion of the anonymous hash and go through each element of it. In my foreach loop, I store each element in $link, and then access the directoryTitle and URL values with a hash slice.
#!/usr/bin/perl use strict; use SOAP::Lite; my $search = SOAP::Lite->service("File:search.wsdl"); my $results = $search->doGoogleSearch( $ENV{GOOGLE_KEY}, 'TPJ', 0, 10, "false", "", "false", "", "latin1", "latin1"); my $links = $results->{resultElements}; foreach my $link ( @$links ) { print join "\n", @{ $link }{ qw(directoryTitle URL) }, "\n"; }
If I want to reinvent Google's "I feel lucky" technology, I fetch only the first result and immediately access the URL with LWP::Simple.
#!/usr/bin/perl use strict; use LWP::Simple; use SOAP::Lite; my $search = SOAP::Lite->service("File:search.wsdl"); my $results = $search->doGoogleSearch( $ENV{GOOGLE_KEY}, 'TPJ', 0, 1, "false", "", "false", "", "latin1", "latin1"); my $link = $results->{resultElements}[0]{URL}; getprint( $link );
Google limits the number of search results I can get back in one query to 10, although the $results anonymous hash does have an estimated count of results in the estimatedTotalResultsCount key. This estimate can be much greater than the total number of results since Google can remove results that are the same as previous results, even though they may have different URLs. If I want to get past the first 10 results, I use a different starting number each time I call doGoogleSearch().
#!/usr/bin/perl use strict; use SOAP::Lite; my $search = SOAP::Lite->service("File:search.wsdl"); for( my ( $start, $total ) = ( 0, 1 ); $start < 50 and $start < $total; $start += 10 ) { my $results = $search->doGoogleSearch( $ENV{GOOGLE_KEY}, 'TPJ', $start, 10, "false", "", "false", "", "latin1", "latin1"); $total = $results->{estimatedTotalResultsCount}; my $links = $results->{resultElements}; foreach my $link ( @$links ) { print join "\n", @{ $link }{ qw(directoryTitle URL) }, "\n"; } }
The Google Web API allows me to easily access the most popular Google features. I can search, then access the results and information about the search without parsing HTML or writing a web client. I did not cover everything that I can do, but the Developer's Kit provides greater detail. Now that you know how simple it is, you have no excuse not to do it yourself.
TPJ