O'Reilly Hacks
oreilly.comO'Reilly NetworkSafari BookshelfConferences Sign In/My Account | View Cart   
Book List Learning Lab PDFs O'Reilly Gear Newsletters Press Room Jobs  

Loop Around the 10-Result Limit
If you want more than 10 results, you'll have to loop
The Code
[Discuss (1) | Link to this hack]

The Code

Save the following code to a text file named looply.pl. Again, remember to replace insert key here with your Google API key, as explained in "Using Your Google API Key" earlier in this chapter.


In addition to the Google API Developer's Kit, you'll need the SOAP::Lite Perl module installed before running this hack.

The alterations to the previous hack needed to support looping through more than the first 10 results are called out in bold.

# looply.pl
# A typical Google Web API Perl script.
# Usage: perl looply.pl <query>
# Your Google API developer's key.
my $google_key='insert key here';
# Location of the GoogleSearch WSDL file.
my $google_wdsl = "./GoogleSearch.wsdl";
# Number of times to loop, retrieving 10 results at a time.
my $loops = 3; # 3 loops x 10 results per loop = top 30 results
use strict;
# Use the SOAP::Lite Perl module.
use SOAP::Lite;
# Take the query from the command line.
my $query = shift @ARGV or die "Usage: perl looply.pl <query>\n";
# Create a new SOAP::Lite instance, feeding it GoogleSearch.wsdl.
my $google_search = SOAP::Lite->service("file:$google_wdsl");
# Keep track of result number.
my $number = 0;for (my $offset = 0; $offset <= ($loops-1)*10; $offset += 10) {
 # Query Google.
 my $results = $google_search -> 
    $google_key, $query, $offset, 10, "false", "", "false",
    "", "latin1", "latin1"
 # No sense continuing unless there are more results.
 last unless @{$results->{resultElements}};
 # Loop through the results.
 foreach my $result (@{$results->{'resultElements'}}) {
  # Print out the main bits of each result.
   join "\n",  
   $result->Loop Around the 10-Result Limit || "no title",
   $result->{snippet} || 'no snippet',

Notice that the script tells Google which set of 10 results it's after by passing an offset ($offset). The offset is increased by 10 each time ($offset +=10).

O'Reilly Home | Privacy Policy

© 2007 O'Reilly Media, Inc.
Website: | Customer Service: | Book issues:

All trademarks and registered trademarks appearing on oreilly.com are the property of their respective owners.