2015-12-21 42 views
0

我在互聯網上嘗試了很多解決方案,但是他們中的每個人都沒有在al案件上工作,我只是想等到元素出現在網頁中, m使用硒爲c# 我嘗試過的兩件事情,他們兩個偶爾會拋出一個異常,我只是不想得到一個異常,我希望我的自動化至少等待5分鐘要加載的網頁。等待至少5分鐘元素出現

public class WaitForElement 
    { 
     public void WaitFE(string Xpath,IWebDriver webDriver) 
     { 
      WebDriverWait wait = new WebDriverWait(webDriver, TimeSpan.FromMinutes(120)); 
      wait.Until(d => d.FindElement(By.XPath(Xpath)).Displayed); 
      //IWebElement category = wait.Until<IWebElement>((d) => 
      //{ 
      // return d.FindElement(By.XPath(Xpath)); 
      //}); 

     } 
    } 
+0

你是否在等待頁面加載後? – Venkatesh

回答

3

的最好的事情是,直到你發現的元素滿足您的所需條件,使用明確的等待:

- 等待了存在的元素:

WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromMinutes(5)); 
      wait.Until(ExpectedConditions.ElementExists(By.XPath(""))); 

- 等待了要顯示的元素:

WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromMinutes(5)); 
      wait.Until(ExpectedConditions.ElementIsVisible(By.XPath(""))); 

- 等待元素點擊

WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromMinutes(5)); 
      wait.Until(ExpectedConditions.ElementToBeClickable(By.XPath(""))); 

或其他你需要的東西。 並通過設置TimeSpan這裏WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromMinutes(5));它將默認等待5分鐘(預期條件爲真的最長時間)。

,你可以做的另一件事,是使用隱式等待作爲默認的最大負載時的所有頁面:

driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromMinutes(5)); 
0

我認爲我解決我的問題,這個等待功能等待大約2分鐘爲元素出現, 誰能告訴我,如果我做的很好

public class WaitForElement 
    { 
     public int count = 0; 
     public void WaitFE(string Xpath,IWebDriver webDriver) 
     { 
      try 
      { 
       while (!(count < 10 && (webDriver.FindElement(By.XPath(Xpath)).Displayed))) 
       { 
        count = 0; 
        return; 
       } 
      } 

      catch 
      { 
       count++; 
       WaitFE(Xpath, webDriver); 
      } 

     }