2014-07-22 99 views
0

我試圖單擊使用Java硒webdriver的彈出窗口中的「保存」按鈕,但它拋出一個異常無法點擊一個按鈕 - Java的硒的webdriver

消息:元素當前不可見和因此可能不會與命令持續時間相關聯

我能夠在彈出窗口中看到「保存」按鈕處於活動狀態。我無法弄清楚它拋出異常的原因。

HTML代碼保存按鈕,我想點擊,

</div> 
<br> 
<br> 
<br> 
<hr> 
<button class="btn btn-primary" style="margin-left: 10px" ng-click="saveData()" data-dismiss="modal" type="button">Save</button> 
<button id="buttonmodalcancel" class="btn btn-default" ng-click="cancel()" type="button">Cancel</button> 
</div> 

firepath:HTML /體/ DIV [6]/DIV/DIV/DIV [2]/DIV/DIV /按鈕[ 1]。

我沒有使用XPath作爲HTML/body/div後的內容,不斷變化。我用

Java代碼:

driver().manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); 
driver().findElementByXPath("//*[contains(text(), 'Save')]").click(); 
+0

拋出什麼異常? – Richard

+0

@Richard,它的ElementNotVisibleException – ASANT

回答

0

首先,你的代碼看起來是錯誤的。 嘗試這一個:

driver.manage().timeouts().implicitlyWait(10, "DefaultTimeOutInSec")), TimeUnit.SECONDS); 
driver.findElement(By.xpath("//*[contains(text(), 'Save')]")).click(); 

driver變量(呼叫)應無大括號中使用;

其次,你可以使用替代CSS選擇器,因爲他們工作得更快:

String buttonCss="button.btn.btn-primary"; 
driver.findElement(By.cssSelector(buttonCss)).click(); 

希望這對你的作品

+0

@ eugene.poschikov,driver()是一個自定義方法,我執行驅動程序的操作,我從父類繼承。但是,在使用您的代碼後,我仍然遇到同樣的錯誤。 – ASANT

+0

即時通訊,如果它拋出元素不可見的異常問題是在你正在定位元素的xpath(定位器),或元素還沒有呈現與它一起操作。你可以使用fluentWait例如來等待你的按鈕像這裏呈現:http://stackoverflow.com/questions/12858972/how-can-i-ask-the-selenium-webdriver-to-wait-for-few-seconds –

+0

感謝eugene。感謝您的迴應。我爲在當前彈出窗口中執行的操作提供了一個名稱,其中保存按鈕始終處於活動狀態,與我提供的名稱無關。 – ASANT

0

我想出了一個辦法來暫時解決問題。我遇到的問題是xpath並不總是相同的,它以指定的模式不斷變化。示例XPath的,我爲一個元素得到,

html/body/div[6]/div/div/div/div/div/div/button[1] html/body/div[5]/div/div/div/div/div/div/button[1] html/body/div[2]/div/div/div/div/div/div/button[1]

由於在格數是我的XPath的唯一變量,我用下面的XPath,

driver().findElement(By.xpath("html/body/div[*]/div/div/div/div/div/div/button[1]")).click(); 
0

當你得到這個錯誤,我建議你檢查xpath或css選擇器是否與一個且僅有的一個元素相關。
我有時會使用點擊第一個顯示元素的方法。基本上,它看起來像(你可能需要糾正它):

public void clickOnFirstDisplayedElement(String path){ 
    // Retrieve all the elements of the page that make sense with the xpath 
    int i = driver.findElements(By.xpath(path)).size(); 
    for(int x = 0; x < i; x++){ 
     int y = x + 1; 
     boolean isDisplayed = driver.findElement(By.xpath(path)).isDisplayed(); 
     if(isDisplayed){ 
      driver.findElement(By.xpath("(" + path + ")[" + y + "]")); 
      x = i; 
     } 
    } 
} 

希望它有幫助。