如何处理selenium Xpath中的条件

时间:2018-02-27 10:35:01

标签: java selenium xpath

我在Web视图中的表中搜索文本,如果文本不存在,则应该转到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. 
}

2 个答案:

答案 0 :(得分:2)

如果你试图寻找一个不存在的元素,那么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

答案 1 :(得分:2)

使用: -

 public boolean isElementPresent(By by) {
  try {
        driver.findElement(by);
      return true;
     } catch (NoSuchElementException e) {
         return false;
    }
}