2017-02-27 44 views
0

運行下面的代碼時,我收到了NoSuchElementException在IF語句中檢查`driver.findElement(...)`拋出`NoSuchElementException`

if (driver.findElement(By.xpath("//*[@id='gr2']")).isDisplayed()) { 
    Thread.sleep(5000); 
    driver.findElement(By.xpath("//*[@id='balInqTableStep2']/td/table/tbody/tr/td/table/tbody/tr[3]/td[4]/input[2]")).click(); 
} 
else { 
    test.log(LogStatus.FAIL,"Please configure Gift Slabs for this site. Contact business."); 
    test.log(LogStatus.FAIL,"Second time wallet credit is not done"); 
} 
+0

你只是想讓我們知道這個信息,或者還有你要問一個問題嗎? – Andersson

+0

你從哪裏得到例外? – Guy

+0

而不是'絕對xpath',嘗試創建'相對xpath',然後再次檢查相同的條件。 –

回答

0

始終當你調用driver.findElement(By.xpath("//*[@id='gr2']"))和元素不存在於DOM,它會拋出一個NoSuchElementException

還有一種方法可以避免代碼拋出異常,調用方法findElements而不是findElement

例如爲:

List<WebElement> elements = driver.findElements(By.xpath("//*[@id='gr2']")); 
if(!elements.isEmpty() && elements.get(0).isDisplayed()) { 
    Thread.sleep(5000); 
    driver.findElement(By.xpath("//*[@id='balInqTableStep2']/td/table/tbody/tr/td/table/tbody/tr[3]/td[4]/input[2]")).click(); 
} 
else { 
    test.log(LogStatus.FAIL,"Please configure Gift Slabs for this site. Contact business."); 
    test.log(LogStatus.FAIL,"Second time wallet credit is not done"); 
} 

希望它爲你工作。

+0

謝謝@Tom其工作 –

1

NoSuchElementException異常意味着頁面上沒有元素存在。

isDisplayed方法假定該元素已經存在於頁面上,當元素不存在時拋出異常。

您可以在調用webdriver方法之前確保該元素存在,並且可以編寫自己的方法來爲您處理此問題。

下面的代碼片段可以幫助你

public boolean isDisplayed(By identifier){ 
    boolean isElementDisplayed = false; 
    try{ 
     WebElement element = driver.findElement(identifier); 
     isElementDisplayed = element.isDisplayed() 
    }catch (NoSuchElementException){ 
     return false; 
    } 

    return isElementDisplayed; 
} 

,你可以這樣調用

isDisplayed(By.xpath("//*[@id='gr2']") 
+0

謝謝@tom其工作 –

+0

@SagarSheth你說湯姆,所以哪個解決方案工作。無論哪種方式,你應該這樣做。 http://stackoverflow.com/help/someone-answers –