Skip to main content

You are here

Add up numbers on a table using Selenium

I made a few assumptions on this one. For example the number of rows. Am sure there is a way to determine the row end. Otherwise watch the console as the code runs. It lists the numbers and adds a sum at the end.

import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.htmlunit.HtmlUnitDriver;
public class AddUpNumbersOnATable {

/*
* The loaded page contains a table for which we want to add up the figures in the Total column
*/
public static void main(String[] args) {
WebDriver driver = new HtmlUnitDriver();
driver.manage().timeouts().implicitlyWait(5,TimeUnit.SECONDS);
driver.get("http://www.infoplease.com/ipa/A0004986.html");  // Actual loading of website
int sumIt =0;
for (int i=2;i<60;i++){
/* not  knowing how many rows will be returned, I have set 60. This number (i) is part of the xpath
as such a NoSuchElement exception will be thrown at some POINT.class This will be trapped by the catch and
execution will continue*/
try{
String s = driver.findElement(By.xpath("//*[@id='Pg']/div[4]/table/tbody/tr["+i+"]/td[12]")).getText();
if(!s.trim().equals("—")){  //some places are "-". Ignore those
System.out.println(s+ "  (at row: "+i+")"); 
sumIt = sumIt + Integer.parseInt(s);
}
} catch (Exception e){
//return;
}
}
System.out.println("-----");
System.out.println(sumIt);
System.out.println("=====");
}
}

Category: 

Language: 

0
No votes yet

Add new comment

Type the characters you see in this picture. (verify using audio)
Type the characters you see in the picture above; if you can't read them, submit the form and a new image will be generated. Not case sensitive.

Disclaimer

Note that the codes and ideas expressed on this site are the authors personal views. The content of this website are the personal notes based on the learning experience of the author. The author will not be responsible for any error or damages resulting from you using the content of this website.

Premium Drupal Themes by Adaptivethemes