Monday, May 16, 2011

Google AppScript URLFetch and Spreasheet Example to Extract Information

Code which pulled all information through urlfetch and load it to spreadsheet.
Simple and cute.



function AddViewCount()
{
  var sheet = SpreadsheetApp.getActiveSheet();
  var prevcount = sheet.getRange(2, 8).getValue();
  prevcount = prevcount + 1;
  sheet.getRange(2, 8).setValue(prevcount);
  SpreadsheetApp.flush();
}

function CollectAllElectionDetails() {
  var sheet = SpreadsheetApp.getActiveSheet();  
  var consttotalcount = 234;
  var rowcount = 1;
  for(var constcount = 1; constcount <= consttotalcount; constcount++)
  {
  var response = UrlFetchApp.fetch("http://eciresults.nic.in/ConstituencywiseS22" + constcount + ".htm");
  var xmldoc = Xml.parse(response.getContentText(), true);
  var root = xmldoc.getElement(); 
  var child1 = root.getElements();
  var bodychilds = child1[1].getElements();
  var bodychilds1 = bodychilds[0].getElements(); 
  var bodychilds11 = bodychilds1[1].getElements();
  var bodychilds111 = bodychilds11[0].getElements();  
  var contestants = bodychilds111[4].getElements();
  var contestantdetails = contestants[0].getElements();
  var call1 = contestantdetails[3].getElements();
  var call11 = call1[1].getElements();
  var call111 = call11[0].getElements("table");
  var cleardetails = Xml.parse(call111[0].toXmlString(), false);
  var rowinfo =  cleardetails.table.tr.td.div.getElements()
  var rowinfo1 =  rowinfo[0].getElements("tr");   
  var constname = rowinfo1[0].td.getText().replace("Tamil Nadu - ","");
  var totalcandidates = rowinfo1.length - 3;
  for(var count=0; count < totalcandidates; count++ )
  {
    var candiname = rowinfo1[count+3].td[0].getText();
    var partyname = rowinfo1[count+3].td[1].getText();
    var totalvotes = rowinfo1[count+3].td[2].getText();
    sheet.getRange(rowcount+1, 1).setValue(constcount);
    sheet.getRange(rowcount+1, 2).setValue(constname);
    sheet.getRange(rowcount+1, 3).setValue(candiname);
    sheet.getRange(rowcount+1, 4).setValue(partyname);
    sheet.getRange(rowcount+1, 5).setValue(totalvotes);
    rowcount++;
  }
} 

}

No comments: