2016-11-08 116 views
-1

我想使用Selenium WebDriver的findElement()函數來檢測頁面上是否存在元素。無論我做什麼,即使拋出WebDriverException,Selenium也會退出代碼。如何使用Java中的Selenium Webdriver檢測元素的存在

我嘗試使用此代碼,但它並沒有阻止硒從離開:

if(driver.findElement(By.xpath(xpath) != null){ 
    driver.findElement(By.xpath(xpath)).click(); 
    System.out.println("Element is Present"); 
}else{ 
    System.out.println("Element is Absent"); 
} 

我在做什麼錯?

isDisplayed()也似乎有一個類似的錯誤。我只是使用了錯誤的方法,或者我錯誤地使用了方法?

+1

使用driver.findElements()。複數形式。這將返回一個列表。檢查大小。如果元素不存在,findElement會引發異常。 – Grasshopper

+0

@Grasshopper它工作完美,謝謝 – KenBone

+0

爲什麼downvotes,我不希望我的新帳戶被禁止,我想我有一個很好的問題,我找不到一個適合我的答案。 – KenBone

回答

0

是的,你可以使用findElements。我給你寫了一個例子如下:

public WebElement element(WebDriver driver) { 
    List<WebElement> list = driver.findElements(By.xpath("xpath")); 
    if (list != null && !list.isEmpty()) { 
     return list.get(0); 
    } 
    return null; 
} 
element.click(); 
+0

完美工作,我不知道爲什麼WebDriver不會正確拋出異常,但這會做。 – KenBone

0

你應該創建一個方法來等待元素,如果它存在或不存在,則返回true或false。這應該爲你做 -

public boolean isElementPresent(final String xpath) { 
    WebDriverWait wait = new WebDriverWait(driver, 30); 
    try { 
    return wait.until(new ExpectedCondition<Boolean>() { 
      public Boolean apply(WebDriver driver) { 
       if (driver.findElement(By.xpath(xpath)).isDisplayed()) { 
        return true; 
       } else { 
        return false; 
       } 
      } 
     });   
    } catch (NoSuchElementException | TimeoutException e) {   
     System.out.println("The wait timed out, couldnt not find element"); 
     return false; 
    }    
} 

這將嘗試30秒,看看元素是否存在或不。將超時從30更改爲無論等待多長時間。

從主代碼

然後發送使用XPath作爲一個字符串,該方法做一些事情,當它回來了真:

if (isElementPresent("xpath")) { 
driver.findElement(By.xpath(xpath)).click(); 
} else { 
    System.out.println("Can't click on the element because it's not there"); 
} 

所以基本上,

如果isElementPresent ==真 - >點擊元素 否則 - >打印出一些東西。

相關問題