2015-12-21 70 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); 
      } 

     }