Error » Search Engines » Google » Google APIs » Google Search API Code Examples

Post New Thread Reply
  Google Search API Code Examples
LinkBack Thread Tools Display Modes
Old 29-Dec-2006, 12:43 AM   #1 (permalink)
Administrator
 
Anilrgowda's Avatar

Posts: 18,715
Join Date: Jan 2006
Rep Power: 10 Anilrgowda is on a distinguished road

IM:
Default Google Search API Code Examples

Simple Search

Here is a code fragment for a simple search. We have pasted in our Google key for you. Try modifying the search string and rerunning the search:
GoogleSearch s = new GoogleSearch();
s.setKey("H/ufNfpQFHIXOhEAuGHVIRl59K66koWo");
s.setQueryString("happiness");
try {
GoogleSearchResult r = s.doSearch();
out.println("<h2>Google Search Results</h2>");
out.println(r.toString());
} catch (Exception f) {
out.println("The call to the Google Web API failed:");
out.println(f.toString());
} Typical Output (Google limits the response to 10 results)
These results aren't documented anywhere that the author could find, but it is apparent that the first attribute returned (TM) is the time spent for the search, and the second attribute (Q) is the search string. The examples that follow perform futher manipulation of the results. The results have been folded so they would not be too wide when displayed.
Google Search Results


{
TM = 0.139481
Q = "happiness"
CT = ""
TT = ""
CATs =
{
{SE="", FVN="Top/Games/Board_Games/Titles/H/Happiness"}
}
Start Index = 1
End Index = 10
Estimated Total Results Number = 1100000
Document Filtering = true
Estimate Correct = false
Rs =
{

[
URL = "http://www.happiness.com/"
Title = "Happiness.com"
Snippet = " ... printed edition. Happiness tips, games, gifts, etc. ...
Spreading Happiness for Over 35 Years". Visit us weekly--New content every Sunday. ... "
Directory Category = {SE="", FVN=""}
Directory Title = ""
Summary = ""
Cached Size = "18k"
Related information present = true
Host Name = ""
],

[
URL = "http://www.thewaytohappiness.org/"
Title = "The Way to Happiness"
Snippet = "The Way to Happiness book is a guide to successful and happy living,
teaches in a way that makes sense and enables you to make intelligent decisions
in life ... "
Directory Category = {SE="",
FVN="Top/Society/Religion_and_Spirituality/Scientology/Church_of_Scientology/Ethics_and_Morals"}
Directory Title = "The Way to Happiness International"
Summary = "A nonprofit organization whose purpose is to disseminate the book "The
Way to Happiness." Suggestions..."
Cached Size = "40k"
Related information present = true
Host Name = ""
],

[
URL = "http://www.amazon.com/exec/obidos/tg/detail/-/1573221112?v=glance"
Title = "Amazon.com: Books: The Art of Happiness: A Handbook for Living"
Snippet = " ... These are the conundrums that psychiatrist Howard Cutler poses to
the Dalai Lama during an extended period of interviews in The Art of Happiness:
A Handbook ... "
Directory Category = {SE="", FVN=""}
Directory Title = ""
Summary = ""
Cached Size = "73k"
Related information present = true
Host Name = ""
],

[
URL = "http://www.amazon.com/exec/obidos/tg/detail/-/B00000IC7G?v=glance"
Title = "Amazon.com: DVD: Happiness (1998)"
Snippet = "Happiness, Todd Solondz, Jane Adams (II), Jon Lovitz, Philip Seymour
Hoffman, Dylan Baker, Lara Flynn Boyle, Justin Elvin, Cynthia Stevenson, Lila
Glantzman ... "
Directory Category = {SE="", FVN=""}
Directory Title = ""
Summary = ""
Cached Size = "65k"
Related information present = true
Host Name = "www.amazon.com"
],

[
URL = "http://www.healthhappiness.com.au/"
Title = "Welcome to Health & Happiness For You"
Snippet = "Health and Happiness for You, view items in shopping cart, ...
Welcome to Health & Happiness For You where we promote the 'experience' of life.
PRODUCT OF THE MONTH. ... "
Directory Category = {SE="",
FVN="Top/Health/Alternative/Holistic_and_Integrated_Medicine"}
Directory Title = "Health and Happiness For You"
Summary = "A journey of self improvement giving answers to those searching for
better lives in a simple plan..."
Cached Size = "28k"
Related information present = true
Host Name = ""
],

[
URL = "http://www.happiness.co.uk/"
Title = "Welcome to The Happiness Project"
Snippet = "Quote of the Moment. "There is a world of difference between searching
for happiness and choosing to be happy.". Robert Holden Happiness is a Way of
Travelling. ... "
Directory Category = {SE="", FVN="Top/Health/Mental_Health/Self-Help"}
Directory Title = "Happiness Project"
Summary = "Designers of the healing and personal development program behind the
BBC documentary 'How to be Happy'...."
Cached Size = "21k"
Related information present = true
Host Name = ""
],

[
URL = "http://www.happiness-is-online.com/"
Title = "Happiness Is - Empower your life with the largest collection of ... "
Snippet = "Famous quotations: beat the blues with the largest collection of
inspirational and motivational quotes about happiness on the web. ... HAPPINESS
QUOTES. ... "
Directory Category = {SE="", FVN="Top/Reference/Quotations/Inspirational"}
Directory Title = "Happiness Is"
Summary = "Collection of inspirational and motivational quotes, arranged
alphabetically."
Cached Size = "59k"
Related information present = true
Host Name = ""
],

[
URL = "http://www.eur.nl/fsw/research/happiness/"
Title = "World Database of Happiness"
Snippet = ""
Directory Category = {SE="",
FVN="Top/Science/Social_Sciences/Psychology/Personality"}
Directory Title = "World Database of Happiness"
Summary = "A continuous register of scientific research on subjective appreciation
of life directed by Ruut Veenhove..."
Cached Size = "1k"
Related information present = true
Host Name = ""
],

[
URL = "http://www.authentichappiness.org/"
Title = "Authentic Happiness - Using the New Positive Psychology"
Snippet = "Authentic Happiness: Using the New Positive Psychology to Realize Your
Potential for Lasting Fulfillment. ... PANAS Questionnaire. General Happiness
Scale. ... "
Directory Category = {SE="", FVN=""}
Directory Title = ""
Summary = ""
Cached Size = "28k"
Related information present = true
Host Name = ""
],

[
URL = "http://www.un-official.com/The_Daily_Script/happiness.txt"
Title = "<html> <head> </head><body><pre>&lt;html&gt; &lt;head&gt; &lt;/ ... "
Snippet = "<html> <head> </head><body><pre>&lt;html&gt; &lt;head&gt;
&lt;/head&gt;&lt;body&gt;&lt;pre&gt; HAPPINESS Written and Directed by Todd
Solondz 1. EXT. ... "
Directory Category = {SE="", FVN="Top/Arts/Movies/Titles/H/Happiness"}
Directory Title = "Un-Official: Happiness"
Summary = "Screenplay for the film by Todd Solondz."
Cached Size = "101k"
Related information present = true
Host Name = ""
]
}
} Simple Search with SafeSearch Enabled

Google's SafeSearch is enabled by default when you use google.com to do a search. You can easily turn it on for a Google Web Services API call:
GoogleSearch s = new GoogleSearch();
s.setKey("H/ufNfpQFHIXOhEAuGHVIRl59K66koWo");
s.setQueryString("happiness");
s.setSafeSearch(true);
try {
GoogleSearchResult r = s.doSearch();
out.println("<h2>Google Search Results</h2>");
out.println(r.toString());
} catch (Exception f) {
out.println("The call to the Google Web API failed:");
out.println(f.toString());
} Spelling Suggestion

Google can offer alternative spellings for search terms. The call returns null if there are no alternative terms:
GoogleSearch s = new GoogleSearch();
s.setKey("H/ufNfpQFHIXOhEAuGHVIRl59K66koWo");
try {
out.println("<h2>Google Spelling Suggestion</h2>");
out.println(s.doSpellingSuggestion("gooogle"));
} catch (Exception f) {
out.println("The call to the Google Web Service API failed:");
out.println(f.toString());
} Result
google
Search Directory Category

GoogleSearch s = new GoogleSearch();
s.setKey("H/ufNfpQFHIXOhEAuGHVIRl59K66koWo");
s.setQueryString("joy");
try {
GoogleSearchResult r = s.doSearch();
out.println("<h2>Google Search Result Categories</h2>");
GoogleSearchDirectoryCategory[] dcs = r.getDirectoryCategories();
for (int i=0; i<dcs.length; i++)
out.println(dcs[i].getFullViewableName());
} catch (Exception f) {
out.println("The call to the Google Web Service API failed:");
out.println(f.toString());
} Results
Top/Arts/Music/Styles/Rock/Gothic/Bands_and_Artists/J/Joy_Division Result Count

You can determine the total number of results returned, as well as an indication of whether this is an exact or an approximate figure.
GoogleSearch s = new GoogleSearch();
s.setKey("H/ufNfpQFHIXOhEAuGHVIRl59K66koWo");
s.setQueryString("love");
try {
GoogleSearchResult r = s.doSearch();
out.println("<h2>Google Search Result Count</h2>");
out.print(r.getEstimateIsExact() ? "Exactly " : "Approximately ");
out.println(r.getEstimatedTotalResultsCount() + " results were found");
} catch (Exception f) {
out.println("The call to the Google Web Service API failed:");
out.println(f.toString());
} Results
Approximately 1030 results were found
Sorted result counts

Here is a variation on the previous example.
String[] arrayDomainNames = {
"www.supremeind.com",
"www.surewest.com",
"www.somersetvalleybank.com",
"www.zoran.com",
"www.zumiez.com",
"www.zygo.com"
};

GoogleSearch s = new GoogleSearch();
s.setKey("lJ9aQ0hQFHJmUeehw9ISh5ZsUYGWOguN");
TreeMap sortedHash = new TreeMap();
int i = 0;
try {
for (i=0; i<arrayDomainNames.length; i++) {
s.setQueryString(arrayDomainNames[i]);
GoogleSearchResult r = s.doSearch();
String domainInfo = arrayDomainNames[i] + " " + (r.getEstimateIsExact() ?"(exact)" :"(approximate)");
sortedHash.put(new Integer(r.getEstimatedTotalResultsCount()), domainInfo);
}
Iterator iterator = sortedHash.keySet().iterator();
System.out.println("<h2>Sorted Google Search Result Count</h2>");
while (iterator.hasNext()) {
Integer key = (Integer)iterator.next();
System.out.println(key + " " + sortedHash.get(key));
}
} catch (GoogleSearchFault gsf) {
System.out.println("Error processing item #" + (i-1) + " + arrayDomainNames[i]; " + gsf);
} Results
This example takes a while to run, and sometimes Google coughs up an error message. If that happens, just try running the example again.
Sorted Google Search Result Count

176 www.somersetvalleybank.com (approximate)
664 www.supremeind.com (approximate)
11900 www.zygo.com (approximate)
16500 www.zumiez.com (approximate)
19600 www.zoran.com (approximate)
52600 www.surewest.com (approximate) Search Time

You can easily discover how many seconds a search took:
GoogleSearch s = new GoogleSearch();
s.setKey("H/ufNfpQFHIXOhEAuGHVIRl59K66koWo");
s.setQueryString("love");
try {
GoogleSearchResult r = s.doSearch();
out.println("<h2>Google Search Time</h2>");
out.println(r.getSearchTime() + " seconds.");
} catch (Exception f) {
out.println("The call to the Google Web API failed:");
out.println(f.toString());
} Results
0.278451 seconds.
Paging Through Results

Although the Google Web Services API only returns 10 results at a time, you can page through the results by setting the starting index:
GoogleSearch s = new GoogleSearch();
s.setKey("H/ufNfpQFHIXOhEAuGHVIRl59K66koWo");
s.setQueryString("peace");
s.setStartResult(42);
try {
GoogleSearchResult r = s.doSearch();
out.println("<h2>Google Search Results</h2>");
out.println(r.toString());
} catch (Exception f) {
out.println("The call to the Google Web API failed:");
out.println(f.toString());
} Results Similar to the first example's results, with Start Index = 42
Detailed Search Results

You can obtain detailed information about the search results, such as the URL they came from, the title of the documents they were retrieved from, a snippet of HTML code describing the document, and the size of the returned search result:
&lt;ilayer src="/JspExplorer/surveys/survey1.html"&gt; &lt;/ilayer&gt; GoogleSearch s = new GoogleSearch();
s.setKey("H/ufNfpQFHIXOhEAuGHVIRl59K66koWo");
s.setQueryString("prosperity");
try {
GoogleSearchResult r = s.doSearch();
out.println("<h2>Google Detailed Search Results</h2>");
GoogleSearchResultElement[] gsres = r.getResultElements();
for (int i=0; i<gsres.length; i++)
out.println(gsres[i].toString());
} catch (Exception f) {
out.println("The call to the Google Web API failed:");
out.println(f.toString());
} Results
Ten formatted paragraphs similar to this one:
[
URL = "http://www.yourprosperity.com.au/"
Title = "Visitor"
Snippet = ""
Directory Category = {SE="",
FVN="Top/Regional/Oceania/Australia/Business_and_Economy/Financial_Services/
Share_Trading/Stockbrokers/Online_Trading"}
Directory Title = "Your Prosperity"
Summary = "The subsidiary of MLC Holdings Limited offers services in share
trading through JDV, fund trading,..."
Cached Size = "1k"
Related information present = true
Host Name = ""
]
Anilrgowda is offline  
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!Spurl this Post!Reddit!
Reply With Quote
   


   
Post New Thread Reply


Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On
Forum Jump


All times are GMT -8. The time now is 04:56 AM.

Powered by vBulletin® Version 3.7.2
Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Search Engine Friendly URLs by vBSEO 3.2.0

DMCA Policy

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228