在硒中添加Webelements

时间:2016-03-29 00:51:48

标签: selenium

我需要捕获webelements的值并找到元素的总和并验证总数是否正确。以下是我的代码:

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);

这里无法添加depCost和arrCost,因为它们是webelements而且' +'操作不能用于webelements是否可以选择对值进行求和。

enter image description here

1 个答案:

答案 0 :(得分:1)

首先需要从WebElement获取文本,然后将文本解析为数字:

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;

将WebElement解析为Float的函数:

static Float Parse(WebElement element) {
  return Float.parseFloat(element.getText().trim());
}