rossmcm
rossmcm

Reputation: 5640

A Google apps javascript function to return the number of hits for a search term

How would I go about implementing a Google app script for returning the number of hits from a Google search? Specifically I have a Google spreadsheet where the formula in cell A2 is =GOOGLEHITS (A1).

I've got as far as:

function GoogleHits (keywords) 
{
return ??? ("\"" + keywords + "\"") ;
}

and would like to know what "???" should be replaced with

Upvotes: 0

Views: 529

Answers (1)

Mogsdad
Mogsdad

Reputation: 45750

Let's assume that you're looking for a way to pull the Results Count off of a Google Search page. First, figure out where that is contained in the page. In Firefox, for example, you can do so using the Inspector (Inspect Element).

Screenshot

There have been previous questions about parsing info out of web pages, and it's quite easily done using the UrlFetch and Xml Services. Refer to these other questions for some background, and the handy-dandy getDivById() function that simplifies your solution.

Code

The GoogleHits function may be used as a custom function from sheets. The test function calls it directly.

function test_GoogleHits() {
  function test( keywords ) {
    Logger.log( keywords + ' : ' + GoogleHits(keywords) );
  }

  test('googlehits');
  test('pizza');
  test('today\'s weather' );
}

function GoogleHits(keywords) {
  var target = "https://www.google.ca/search?q="+encodeURI(keywords);

  var pageTxt = UrlFetchApp.fetch(target).getContentText();
  var pageDoc = Xml.parse(pageTxt,true);
  var contentDiv = getDivById( pageDoc.getElement().body, 'resultStats' );
  return extractInteger( contentDiv.Text );
}

function extractInteger(str) {
  var num = "";
  var inNum = false;
  for(var i=0; i<str.length; i++) {
    var c = str.charAt(i);
    if (c>='0' && c<= '9') {
      if (!inNum) inNum = true;
      num += c;
    }
    else if (c !== ',') {
      if (inNum) break;
    }
  }
  return parseInt(num);
}

Upvotes: 1

Related Questions