2015-01-08 139 views
3

我使用的Selenium WebDriver與一個框架(黃瓜)實現,我面臨一個問題,等待一個元素被加載之前執行一個動作。如何在沒有By定位器的情況下使用WebDriverWait.until?

最初,我想使用隱式等待,但如果一個元素沒有立即加載,它會等待超時。通常情況下,它使我的測試時間比我想要的要長。

然後,我想使用顯式等待來儘可能縮短每個案例的等待時間。 問題是WebDriverWait.until中的ExpectedConditions上的大多數元素都在尋找位於By定位器(它們是ClassName,CssSelector,Id,LinkText,Name,PartialLinkText,Tagname或XPath)的元素。 我在用於點擊webelement的常規函數​​中使用WebDriverWait.until。 我測試的網站上的webelements是由dojo生成的,沒有靜態ID。它們並不總是具有其他類型的定位器,或者它們不是靜態的。 開發人員然後向webelement添加了一個名爲data-automation-id的附加屬性。我想在明確的等待中使用這個屬性,但是找不到一種方法來做到這一點。

我嘗試使用以下代碼來使用XPath:

public void clickOnDataAutomationId(String dataautomationid) { 
    WebDriverWait wait = new WebDriverWait(driver, 10); 
    WebElement element = wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//" + findDataAutomationId(dataautomationid).getAttribute("tagName") + "[contains(@data-automation-id, '" + dataautomationid + "')]"))); 
    findDataAutomationId(dataautomationid).click(); 
} 

findDataAutomationId()是返回包含所述數據的自動化-ID作爲FluentWebElement第一webelement的功能。

問題是如果webelement沒有立即加載,findDataAutomationId會失敗,這會使WebDriverWait.until無意義。您是否看到另一種方法來解決By Locators在不重構網站的情況下?

+0

請發表您的findDataAutomationId片斷 –

+0

這就是: 公共FluentWebElement findDataAutomationId(字符串dataautomationid){ 回報的FindFirst(getDataAutomationId(dataautomationid)); (DataAutomationID = {0}]「,dataautomationid);返回format(」[data-automation-id = {0}]「。 } –

回答

2

而不是使用方法findDataAutomationId檢索webelement,你可以直接找到webeelement,然後點擊它,如下圖所示:

public void clickOnDataAutomationId(String dataautomationid) { 
    WebDriverWait wait = new WebDriverWait(driver, 10); 
    WebElement element = wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[contains(@data-automation-id, '" + dataautomationid + "')]"))); 
    element.click(); 
} 

,或者,如果數據自動化-ID是一個完整的文本,而不是一個組成部分,那麼你可以使用下面的代碼:

public void clickOnDataAutomationId(String dataautomationid) { 
    WebDriverWait wait = new WebDriverWait(driver, 10); 
    WebElement element = wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[@data-automation-id, '" + dataautomationid + "')]"))); 
    element.click(); 
} 
+0

明智的是,解決方案與在Xpath中用「*」替換findDataAutomationId()。getAttribute()一樣簡單。非常感謝你。 事實上,使用webelement而不是使用findDataAutomationId()再次檢索它更清潔。 –

+0

很高興爲你工作..乾杯.. :) – Subh

0

使用「presenceOfElementLocated」方法而不是「elementToBeClickable」。這種變化可能會幫助你

+0

presenceOfElementLocated也使用定位器,所以它的工作允許我尋找具有data-automation-id屬性的webelements。 問題不在於條件的類型,而在於我可以使用的定位器的類型。 –

0

你下面的解決方案。它不會返回,直到申請()爲真或直到等待超時

WebDriverWait wait = new WebDriverWait(driver, 10); 
wait.until(new Function<WebDriver, Object>() { 
       @Nullable 
       public Object apply(@Nullable WebDriver input) { 
//add any condition or check your data-automation-id is visible/clickable 
        return true; 
       } 
      }); 
    } 
相關問題