我正在 Web View 中的表格中搜索文本,如果文本不存在,它应该转到 else 并相应地执行我的操作,而不是这样,它会抛出 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
关于java - 如何处理 selenium Xpath 中的条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49006574/