Previous Section  < Day Day Up >  Next Section

Hack 40. Run a Google Popularity Contest

Put two terms, spelling variations, animals, vegetables, or minerals head to head in a Google-based popularity contest.

Which is the most popular word? Which spelling is more commonly used? Who gets more mentions, Fred or Ethel Mertz? These and other equally critical questions are answered by Google Smackdown (http://www.onfocus.com/googlesmack/down.asp).

Google Smackdown was written by Paul Bausch (http://www.onfocus.com/).


Why would you want to compare search counts? Sometimes finding out which terms appear more often can help you develop your queries better. Why use a particular word if it gets almost no results? Comparing misspellings can provide leads on hard-to-find terms or phrases. And sometimes it's just fun to run a popularity contest.

If you're just searching for keywords, Google Smackdown is very simple. Enter one word in each query box, a Google Web API developer's key [Chapter 9] if you have one, and click the "throw down!" button. Smackdown will return the winner and approximate count of each search.

If you're planning to use a special syntax, you'll have to be more careful. Unfortunately, the link: syntax doesn't work. Interestingly, phonebook: does; do more people named Smith or Jones live in Boston, MA?

To use any special syntaxes, enclose the query in quotes: "intitle:windows".

The next tip is a little backwards. If you want to specify a phrase, do not use quotes; Smackdown, by default, searches for a phrase. If you want to search for the two words on one page but not necessarily as a phrase (jolly and roger versus "jolly roger"), do use quotes. The reason the special syntaxes and phrases work this way is because the program automatically encloses phrases in quotes, and if you add quotes, you're sending a double quoted query to Google (""Google""). When Google runs into a double quote like that, it just strips out all the quotes.

If you'd like to try a Google Smackdown without having to run it yourself, there's a live version available at: http://www.onfocus.com/googlesmack/down.asp.


2.22.1. The Code

Google Smackdown is written for ASP pages running under the Windows operating system and Microsoft Internet Information Server (IIS):

<% 

'-----------------------------------------------------------

' Set the global variable strGoogleKey. 

'-----------------------------------------------------------

Dim strGoogleKey

strGoogleKey = "you rkey goes here. "

'-----------------------------------------------------------

' The function GetResult( ) is the heart of Google Smackdown. 

' It queries Google with a given word or phrase and returns 

' the estimated total search results for that word or phrase. 

' By running this function twice with the two words the user 

' enters into the form, we have our Smackdown.

'-----------------------------------------------------------

Function GetResult(term)

 '-----------------------------------------------------------

 ' Set the variable the contains the SOAP request. A SOAP 

 ' software package will generate a similar request to this

 ' one behind the scenes, but the query for this application

 ' is very simple so it can be set "by hand."

 '-----------------------------------------------------------

 strRequest = "<?xml version='1.0' encoding='UTF-8'?>" & Chr(13) & Chr(10) 

& Chr(13) & Chr(10)

 strRequest = strRequest & "<SOAP-ENV:Envelope xmlns:SOAP-ENV=""http://schemas.

xmlsoap.org/soap/envelope/"" xmlns:xsi=""http://www.w3.org/1999/XMLSchema-instance"" 

xmlns:xsd=""http://www.w3.org/1999/XMLSchema"">" & Chr(13) & Chr(10)

 strRequest = strRequest & " <SOAP-ENV:Body>" & Chr(13) & Chr(10)

 strRequest = strRequest & " <ns1:doGoogleSearch xmlns:ns1=""urn:GoogleSearch"" 

SOAP-ENV:encodingStyle=""http://schemas.xmlsoap.org/soap/encoding/"">" & Chr(13) 

& Chr(10)

 strRequest = strRequest & "  <key xsi:type=""xsd:string"">" & strGoogleKey 

& "</key>" & Chr(13) & Chr(10)

 strRequest = strRequest & "  <q xsi:type=""xsd:string"">""" & term & 

"""</q>" & Chr(13) & Chr(10)

 strRequest = strRequest & "  <start xsi:type=""xsd:int"">0</start>" 

& Chr(13) & Chr(10)

 strRequest = strRequest & "  <maxResults xsi:type=""xsd:int"">1</

maxResults>" & Chr(13) & Chr(10)

 strRequest = strRequest & "  <filter xsi:type=""xsd:boolean"">true</

filter>" & Chr(13) & Chr(10)

 strRequest = strRequest & "  <restrict xsi:type=""xsd:string""></

restrict>" & Chr(13) & Chr(10)

 strRequest = strRequest & "  <safeSearch xsi:type=""xsd:boolean"">false</

safeSearch>" & Chr(13) & Chr(10)

 strRequest = strRequest & "  <lr xsi:type=""xsd:string""></lr>" & 

Chr(13) & Chr(10)

 strRequest = strRequest & "  <ie xsi:type=""xsd:string"">latin1</ie>" 

& Chr(13) & Chr(10)

 strRequest = strRequest & "  <oe xsi:type=""xsd:string"">latin1</oe>" 

& Chr(13) & Chr(10)

 strRequest = strRequest & " </ns1:doGoogleSearch>" & Chr(13) & Chr(10)

 strRequest = strRequest & " </SOAP-ENV:Body>" & Chr(13) & Chr(10)

 strRequest = strRequest & "</SOAP-ENV:Envelope>" & Chr(13) & Chr(10)

 '----------------------------------------------------------- 

 ' The variable strRequest is now set to the SOAP request.

 ' Now it's sent to Google via HTTP using the Microsoft

 ' ServerXMLHTTP component. 

 '

 ' Create the object... 

 '----------------------------------------------------------- 

 Set xmlhttp = Server.CreateObject("MSXML2.ServerXMLHTTP")

 

 '-----------------------------------------------------------

 ' Set the variable strURL equal to the URL for Google Web

 ' Services.

 '-----------------------------------------------------------

 strURL = "http://api.google.com/search/beta2"

 

 '----------------------------------------------------------- 

 ' Set the object to open the specified URL as an HTTP POST.

 '----------------------------------------------------------- 

 xmlhttp.Open "POST", strURL, false

 

 '----------------------------------------------------------- 

 ' Set the Content-Type header for the request equal to

 ' "text/xml" so the server knows we're sending XML.

 '----------------------------------------------------------- 

 xmlhttp.setRequestHeader "Content-Type", "text/xml"

 

 '----------------------------------------------------------- 

 ' Send the XML request created earlier to Google via HTTP.

 '----------------------------------------------------------- 

 xmlhttp.Send(strRequest)

 

 '----------------------------------------------------------- 

 ' Set the object AllItems equal to the XML that Google sends

 ' back. 

 '----------------------------------------------------------- 

 Set AllItems = xmlhttp.responseXML

 

 '-----------------------------------------------------------

 ' If the parser hit an error--usually due to malformed XML, 

 ' write the error reason to the user. And stop the script.

 ' Google doesn't send malformed XML, so this code shouldn't 

 ' run.

 '-----------------------------------------------------------

 If AllItems.parseError.ErrorCode <> 0 Then

  response.write "Error: " & AllItems.parseError.reason

  response.end

 End If

 

 '-----------------------------------------------------------

 ' Release the ServerXMLHTTP object now that it's no longer

 ' needed--to free the memory space it was using.

 '-----------------------------------------------------------

 Set xmlhttp = Nothing

 

 '-----------------------------------------------------------

 ' Look for <faultstring> element in the XML the google has 

 ' returned. If it exists, Google is letting us know that 

 ' something has gone wrong with the request. 

 '-----------------------------------------------------------

 Set oError = AllItems.selectNodes("//faultstring")

 If oError.length > 0 Then

  Set oErrorText = AllItems.selectSingleNode("//faultstring")

  GetResult = "Error: " & oErrorText.text

  Exit Function

 End If

 

 '-----------------------------------------------------------

 ' This is what we're after: the <estimatedTotalResultsCount>

 ' element in the XML that Google has returned. 

 '-----------------------------------------------------------

 Set oTotal = AllItems.selectSingleNode("//estimatedTotalResultsCount")

 GetResult = oTotal.text

 Set oTotal = Nothing

 

End Function

'-----------------------------------------------------------

' Begin the HTML page. This portion of the page is the same

' for both the initial form and results.

'-----------------------------------------------------------

%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">

<html>

<head>

 <title>Google Smackdown</title>

 <meta http-equiv="Content-Type" content="text/html; charset=utf-8">

 <script language="JavaScript">

  // This client-side JavaScript function validates user input.

  // If the form fields are empty when the user clicks "submit"

  // this will stop the submit action, and prompt the user to 

  // enter some information.

  function checkForm( ) {

   var f = document.frmGSmack

   if ((f.text1.value == '') || (f.text1.value == ' ')) {

    alert('Please enter the first word or phrase.')

    return false;

   } 

   if ((f.text2.value == '') || (f.text2.value == ' ')) {

    alert('Please enter the second word or phrase.')

    return false;

   } 

   return true;

  }

 </script> 

</head>

<body>

<h1>Google Smackdown</h1>

This queries Google via its API and receives the estimated total results for each word or 

phrase.

<%

'-----------------------------------------------------------

' If the form request items "text1" and "text2" are not

' empty, then the form has been submitted to this page.

'

' It's time to call the GetResult( ) function and see which

' word or phrase wins the Smackdown.

'-----------------------------------------------------------

If request("text1") <> "" AND request("text2") <> "" Then

 '-----------------------------------------------------------

 ' Send the word from the first form field to GetResult( ), 

 ' and it will return the estimated total results. 

 '-----------------------------------------------------------

 intResult1 = GetResult(request("text1"))

 

 '-----------------------------------------------------------

 ' Check to make sure the first result is an integer. If not, 

 ' Google has returned an error message and the script will 

 ' move on. 

 '-----------------------------------------------------------

 If isNumeric(intResult1) Then

  intResult2 = GetResult(request("text2"))

 End If

 

 '-----------------------------------------------------------

 ' Check to make sure the second result is also an integer.

 ' If they're both numeric, the script can display the 

 ' results. 

 '-----------------------------------------------------------

 If isNumeric(intResult1) AND isNumeric(intResult2) Then

  intResult1 = CDbl(intResult1)

  intResult2 = CDbl(intResult2)

  

  '-----------------------------------------------------------

  ' Begin writing the results to the page...

  '-----------------------------------------------------------

  response.write "<h2>The Results</h2>"

  response.write "And the undisputed champion is...<br>"

  response.write "<ol>"

  

  '-----------------------------------------------------------

  ' Compare the two results to determine which should be 

  ' displayed first.

  '-----------------------------------------------------------

  If intResult1 > intResult2 Then

   response.write "<li>" & request("text1") & " (<a target=""_blank"" 

href=""http://www.google.com/search?hl=en&ie=UTF8&oe=UTF8&q=" & Server.

URLEncode("""" & request("text1") & """") & """>" & FormatNumber

(intResult1,0) & "</a>)<br>"

   response.write "<li>" & request("text2") & " (<a target=""_blank"" 

href=""http://www.google.com/search?hl=en&ie=UTF8&oe=UTF8&q=" & Server.

URLEncode("""" & request("text2") & """") & """>" & FormatNumber

(intResult2,0) & "</a>)<br>"

  Else

   response.write "<li>" & request("text2") & " (<a target=""_blank"" 

href=""http://www.google.com/search?hl=en&ie=UTF8&oe=UTF8&q=" & 

Server.URLEncode("""" & request("text2") & """") & """>" & FormatNumber

(intResult2,0) & "</a>)<br>"

   response.write "<li>" & request("text1") & " (<a target=""_blank"" 

href=""http://www.google.com/search?hl=en&ie=UTF8&oe=UTF8&q=" & Server.

URLEncode("""" & request("text1") & """") & """>" & FormatNumber

(intResult1,0) & "</a>)<br>"

  End If 

  '-----------------------------------------------------------

  ' Finish writing the results to the page and include a link

  ' to the page for another round.

  '----------------------------------------------------------- 

  response.write "</ol>"

  response.write "<a href=""smackdown.asp"">Another Challenge?</a>"

  response.write "<br>"

 Else

  '-----------------------------------------------------------

  ' One or both of the results are not numeric. We can assume

  ' this is because the developer's key has reached its

  ' 1,000 query limit for the day. Because the script has 

  ' made it to this point, the SOAP response did not return

  ' an error. If it had, GetResult( ) would have stopped the

  ' script. 

  '-----------------------------------------------------------

  intResult1 = Replace(intResult1,"key " & strGoogleKey,"key")

  intResult2 = Replace(intResult2,"key " & strGoogleKey,"key")

  

  '-----------------------------------------------------------

  ' Write out the error to the user...

  '-----------------------------------------------------------

  response.write "<h2>It Didn't Work, Error</h2>"

  '-----------------------------------------------------------

  ' If the results are the same, we don't need to write out

  ' both of them.

  '-----------------------------------------------------------

  If intResult1 = intResult2 Then

   response.write intResult1 & "<br><br>"

  Else

   response.write intResult1 & "<br><br>" & intResult2 & 

"<br><br>"

  End If

  '-----------------------------------------------------------

  ' A link to the script for another round.

  '-----------------------------------------------------------

  response.write "<a href=""smackdown.asp"">Another Challenge?</a>"

  response.write "<br>"

 End If

Else

'-----------------------------------------------------------

' The form request items "text1" and "text2" are empty, 

' which means the form has not been submitted to the page 

' yet.

'-----------------------------------------------------------

%>

<h2>The Arena</h2>

<div class="clsPost">The setting is the most impressive search engine ever built: 

<a href="http://www.google.com/">Google</a>. As a test of its <a href=

"http://www.google.com/apis">API</a>, two words or phrases will go head-to-head 

in a terabyte tug-of-war. Which one appears in more pages across the Web?

<h2>The Challengers</h2>

You choose the warring words...

<br><br>

<form name="frmGSmack" action="smackdown.asp" method="post" onSubmit="return 

checkForm( );">

<table>

 <tr>

  <td align="right">word/phrase 1</td> <td><input type="text" name=

"text1"></td>

 </tr>

 <tr>

  <td align="right">word/phrase 2</td> <td><input type="text

" name="text2"></td>

 </tr>

 <tr>

  <td>&nbsp;</td><td><input type="submit" value="throw down!

"></td>

 </tr>

</table>

</form>

<% 

End If 

'-----------------------------------------------------------

' This is the end of the If statement that checks to see

' if the form has been submitted. Both states of the page

' get the closing tags below.

'-----------------------------------------------------------

%>

</body>

</html>

2.22.2. Running the Hack

The hack is run in exactly the same manner as the live version of Google Smackdown (http://www.onfocus.com/googlesmack/down.asp) running on Onfocus.com. Point your web browser at it and fill out the form. Figure 2-14 shows a sample Smackdown between negative feelings about Macintosh versus Windows.

Figure 2-14. Macintosh/Windows Google Smackdown


    Previous Section  < Day Day Up >  Next Section