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  



HACK
#36
Search Google Topics
Run queries against some of the available Google API specialty topics
The Code
[Discuss (0) | Link to this hack]

The Code

Save the following code as a CGI script ["How to Run the Hacks" in the Preface] named gootopic.cgi in the cgi-bin directory on your web server:

#!/usr/local/bin/perl
# gootopic.cgi
# Queries across Google Topics (and All of Google), returning 
# number of results and top result for each topic.
# gootopic.cgi is called as a CGI with form input
     
# Your Google API developer's key.
my $google_key='insert key here';
     
# Location of the GoogleSearch WSDL file.
my $google_wdsl = "./GoogleSearch.wsdl";
     
# Google Topics
my %topics = (
  ''       => 'All of Google',
  unclesam => 'U.S. Government',
  linux    => 'Linux',
  mac      => 'Macintosh',
  bsd      => 'FreeBSD'
);
     
use strict;
     
use SOAP::Lite;
use CGI qw/:standard *table/;
     
# Display the query form.
print
  header( ),
  start_html("GooTopic"),
  h1("GooTopic"),
  start_form(-method=>'GET'),
  'Query: ', textfield(-name=>'query'), '   ',
  submit(-name=>'submit', -value=>'Search'),
  end_form( ), p( );
     
my $google_search  = SOAP::Lite->service("file:$google_wdsl");
     
# Perform the queries, one for each topic area.
if (param('query')) {
  print 
    start_table({-cellpadding=>'10', -border=>'1'}),
    Tr([th({-align=>'left'}, ['Topic', 'Count', 'Top Result'])]);
     
  foreach my $topic (keys %topics) {
     
    my $results = $google_search -> 
      doGoogleSearch(
        $google_key, param('query'), 0, 10, "false", $topic,  "false",
        "", "latin1", "latin1"
      );
     
    my $result_count = $results->{'estimatedTotalResultsCount'};
     
    my $top_result = 'no results';
     
    if ( $result_count ) {
      my $t = @{$results->{'resultElements'}}[0];
      $top_result = 
        b($t->Search Google Topics||'no title') . br( ) .
        a({href=>$t->{URL}, $t->{URL}}) . br( ) .
        i($t->{snippet}||'no snippet');
    }
   
    # Output
    print Tr([ td([
      $topics{$topic},
      $result_count,
      $top_result
      ])
    ]);
  }
     
  print 
    end_table( ),
}
     
print end_html( );

Be sure to replace insert key here with your Google API key.


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.