2016-08-23 38 views
-1

我試圖單擊使用id的按鈕,然後使用class名稱,然後xpath,id會動態給出。你能告訴我確切的XPath此代碼使用xpath在黃瓜中單擊按鈕

package step_definitions; 

import org.openqa.selenium.By; 
import org.openqa.selenium.WebDriver; 
import cucumber.api.java.en.Given; 
import cucumber.api.java.en.Then; 
import cucumber.api.java.en.When; 

public class sharedshelf { 
    public WebDriver driver; 
    public sharedshelf() 
    { 
     driver = Hooks.driver; 
    } 
@When("^I press option button$") 
    public void i_press_option_buttion() throws Throwable { 
     // Write code here that turns the phrase above into concrete actions 
     Thread.sleep(5000); 
     driver.findElement(By.xpath("//button[text()='Edit']")).click(); 
    } 

的Html

<button type="button" id="ext-gen494" class=" x-btn-text" tabindex="4">Edit</button> 
+0

你有什麼錯誤? – Guy

+0

您的xpath看起來正確。那有什麼問題?有什麼異常嗎? –

+0

org.openqa.selenium.InvalidElementStateException:無效的元素狀態 它顯示這個 – ali

回答

0

一個例外可能會在這些情況下,元素上點擊時拋出: 如果元素被禁用,硒嘗試點擊 - 它不自動等待,直到它可點擊 也可能發生如果元素不可見/元素不可點擊(隱藏在另一個元素下) 等待元素可點擊的解決方案(在等待直到可見和啓用的引擎蓋下)將不會解決陳舊元素參考例外 http://docs.seleniumhq.org/exceptions/stale_element_reference.jsp

,最好的辦法是創建這樣的方法:

public void TryClick(By by) 
    { 
     DateTime timeout = DateTime.Now.AddSeconds(10); 
     bool clickedSuccessfully = false; 
     Exception exceptionWhileClick = null; 
     do 
     { 
      try 
      { 
       WrappedElement.FindElement(by).Click(); 
       clickedSuccessfully = true; 
      } 
      catch (Exception e) 
      { 
       // ignored 
       exceptionWhileClick = e; 
      } 
     } while (!clickedSuccessfully && DateTime.Now < timeout); 

     if (!clickedSuccessfully && exceptionWhileClick != null) 
      throw exceptionWhileClick; 

    } 
0

的按鈕是不是當你嘗試一下就可以了點擊。嘗試等待按鈕可點擊。

您也可以使用定位由部分ID按鈕cssSelectorBy.cssSelector("[id*='ext']")

WebDriverWait wait = new WebDriverWait(driver, 10); 
WebElement button = wait.until(ExpectedConditions.elementToBeClickable(By.cssSelector("[id*='ext']"))); 
button.click();