1

I need to capture values of webelements and find the sum of the elements and verify if the total is correct. Below is my code:

WebElement depCost = driver.findElement(By.xpath("html/body/div[1]/table/tbody/tr/td[2]/table/tbody/tr[4]/td/table/tbody/tr/td[2]/table/tbody/tr[5]/td/form/table/tbody/tr[2]/td/table/tbody/tr[3]/td[3]/font"));

WebElement arrCost = driver.findElement(By.xpath("html/body/div[1]/table/tbody/tr/td[2]/table/tbody/tr[4]/td/table/tbody/tr/td[2]/table/tbody/tr[5]/td/form/table/tbody/tr[2]/td/table/tbody/tr[6]/td[3]/font"));

WebElement numOfPass = driver.findElement(By.xpath("html/body/div[1]/table/tbody/tr/td[2]/table/tbody/tr[4]/td/table/tbody/tr/td[2]/table/tbody/tr[5]/td/form/table/tbody/tr[2]/td/table/tbody/tr[7]/td[2]/font"));

WebElement taxes = driver.findElement(By.xpath("html/body/div[1]/table/tbody/tr/td[2]/table/tbody/tr[4]/td/table/tbody/tr/td[2]/table/tbody/tr[5]/td/form/table/tbody/tr[2]/td/table/tbody/tr[8]/td[2]/font"));

WebElement total = driver.findElement(By.xpath("html/body/div[1]/table/tbody/tr/td[2]/table/tbody/tr[4]/td/table/tbody/tr/td[2]/table/tbody/tr[5]/td/form/table/tbody/tr[2]/td/table/tbody/tr[9]/td[2]/font/b"));

Float sumTotal=(((depCost + arrCost)*numOfPass)+taxes);

Here it is not able to add depCost and arrCost as they are webelements and '+'operation cannot be done for webelements is there an alternative to sum the values.

enter image description here

1 Answer 1

1

You first need to get the text from the WebElement, and then parse the text to a number:

Float arrCost = Parse(driver.findElement(By.xpath("...")));
Float numOfPass = Parse(driver.findElement(By.xpath("...")));
Float taxes = Parse(driver.findElement(By.xpath("...")));
Float total = Parse(driver.findElement(By.xpath("...")));

Float sumTotal= ((depCost + arrCost) * numOfPass) + taxes;

And the function to parse a WebElement to a Float:

static Float Parse(WebElement element) {
  return Float.parseFloat(element.getText().trim());
}
Sign up to request clarification or add additional context in comments.

2 Comments

I was able to fetch the other values .Its now throwing the following error for $44 : Exception in thread "main" java.lang.NumberFormatException: For input string: "$44" at java.lang.NumberFormatException.forInputString(Unknown Source)
"$44" is not a number. Replace .trim() by .replaceAll("[^+-.\\d]+", "") to extract the number.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.