我正在Web视图的表中搜索文本,如果文本不存在,则应转到其他位置并相应地执行我的操作,而不是此方法,它引发NoSuchElementException异常。如何处理。找不到要比较的数据时,哪些Web驱动程序将返回值。
注意:如果在表中找到title
变量的匹配值,则此方法很好
WebElement table = driver.findElement(By.xpath("html/body/form/div[6]/div/div[1]/div[2]/fieldset/div[1]/div/div[1]/div/table"));
// find the row
WebElement customer = table.findElement(By.xpath("//tbody/tr/td[contains(text(), '"+title+"')]/following-sibling::td/a[text()='Detail']"));
if(customer != null){ // how do I compare here.
//System.out.println("This is your TITLE " +customer.getText());
}else{
// my further code for failed case.
}
最佳答案
如果尝试查找不存在的元素,则确实会抛出NoSuchElementException
。因此,使用try / catch
机制以定义else
情况:
WebElement table = driver.findElement(By.xpath("html/body/form/div[6]/div/div[1]/div[2]/fieldset/div[1]/div/div[1]/div/table"));
try {
WebElement customer = table.findElement(By.xpath("//tbody/tr/td[contains(text(), '"+title+"')]/following-sibling::td/a[text()='Detail']"));
System.out.println("This is your TITLE " +customer.getText());
}
catch(NoSuchElementException e) {
// code for failed case
}
或者,您可以检查元素是否存在,然后应用常规的
if / else
:WebElement table = driver.findElement(By.xpath("html/body/form/div[6]/div/div[1]/div[2]/fieldset/div[1]/div/div[1]/div/table"));
int amount = table.findElements(By.xpath("//tbody/tr/td[contains(text(), '"+title+"')]/following-sibling::td/a[text()='Detail']")).size();
if(amount > 0)
// element exists
else
// element doesn't exist