2016-01-23 56 views
2

我正在嘗試編寫一個通用Web驅動程序等待等待元素可點擊。但是我發現了網絡驅動程序等待寫入特定於By.id或By.name的等待。如何在Selenium中編寫通用Web驅動程序等待

假設下面是兩個WebElements

public WebElement accountNew() { 
    WebElement accountNew = driver.findElement(By.xpath("//input[@title='New']")); 
    waitForElementtobeClickable(accountNew); 
    return accountNew; 
} 

public WebElement accountName() { 
    WebElement accountName = driver.findElement(By.id("acc2")); 
    waitForElementtobeClickable(accountName); 
    return accountName; 
} 

下面是廣義waitofrelementtobeclickable。

public static void waitForElementtobeClickable(WebElement element) {   
     try { 
      WebDriverWait wait = new WebDriverWait(driver, 10); 
      wait.until(ExpectedConditions.elementToBeClickable(element)); 
      System.out.println("Got the element to be clickable within 10 seconds" + element); 
     } catch (Exception e) { 
      WebDriverWait wait1 = new WebDriverWait(driver, 20); 
      wait1.until(ExpectedConditions.elementToBeClickable(element)); 
      System.out.println("Got the element to be clickable within 20 seconds" + element); 
      e.printStackTrace(); 
     } 
    } 

但它似乎沒有工作。任何關於如何爲xpath,或id,或class或Css寫一個通用代碼的建議都可以寫出來?

+0

做什麼你的意思是「似乎不起作用」?你有錯誤嗎? – Guy

+0

不,沒有錯誤,但對waitforelementclickable的調用只是繞過,並沒有通過實際等待10或20秒的過程。示例:登錄到Salesforce應用程序後,我希望頂部面板中的userName是可點擊的,以便我可以點擊它,然後單擊註銷。但是登錄後頁面仍然正在加載,程序只是終止,說找不到元素。但是如果我給出20秒的明確睡眠,它就會起作用。所以xpath/locator不是問題。 – Ronnie

回答

1

這個問題不在你的函數中,它在你的driver.findElement中,因爲你試圖在元素存在於DOM之前找到它。您可以使用隱式等待

driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); 

這將等待10秒在DOM定位時,之前存在的任何元素。

或者使用顯式的等待

WebDriverWait wait = new WebDriverWait(driver, 10); 
WebElement element = wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//input[@title='New']"))); 

找到你的元素這將等待長達10秒鐘的元素是可見的。

你當然可以(也應該)同時使用。

您可以更改您的代碼以類似的東西

public static WebElement waitForElementtobeClickable(By by) { 
    WebDriverWait wait = new WebDriverWait(driver, 10); 
    WebElement element = wait.until(ExpectedConditions.elementToBeClickable(by)); 
    System.out.println("Got the element to be clickable within 10 seconds" + element); 
    return element; 
} 

public WebElement accountNew() { 
    WebElement accountNew = waitForElementtobeClickable(By.xpath("//input[@title='New']")); 
    return accountNew; 
} 

您發送您的By定位器waitForElementtobeClickable和使用elementToBeClickable(By)代替elementToBeClickable(WebElement),這樣你就可以使用XPath,ID,類等

+0

非常感謝。像魅力一樣工作。我其實已經有了一個想法,但卻無法讓我的頭腦去實現它。也因爲我沒有使用Page Factory模型而感到困惑,並且只使用一個靜態驅動程序,該驅動程序在BasePage類中聲明。 – Ronnie

+0

@羅尼很高興工作。通過點擊附近的綠色複選標記,隨意接受此答案作爲解決方案;) – Guy

相關問題