【问题标题】:Is there any better Sleep() method than Thread.Sleep()?有没有比 Thread.Sleep() 更好的 Sleep() 方法?
【发布时间】:2020-03-03 23:45:50
【问题描述】:

假设我正在尝试查找名为 element0 的元素,

driver.FindElement(element0).Click;
Thread.Sleep(5000);

根据我的 WiFi 速度,element0 可能需要 5000 到 10000 毫秒才能显示出来。

必须不断更改 Thread.Sleep() 中的值会破坏自动化的目的。

将它包围在 try catch 块周围可能会起作用:

try
{
   driver.FindElement(element0).Click;
   Thread.Sleep(5000);
} 
catch(org.openqa.selenium.NoSuchElementException e)
{
   driver.FindElement(element0).Click;
   Thread.Sleep(5000);
}

但是如果在捕获org.openqa.selenium.NoSuchElementException e 之后element0 仍然不存在,那么它只会抛出另一个相同的错误。

有没有更好的方法让我的代码进入睡眠状态?

我可以循环遍历driver.FindElement(element0).Click 直到出现element0 吗?

【问题讨论】:

    标签: java android automation appium sleep


    【解决方案1】:

    硒气体显式等待

    import org.openqa.selenium.support.ui.ExpectedConditions;
    import org.openqa.selenium.support.ui.WebDriverWait;
    
    WebDriverWait wait = new WebDriverWait(WebDriverRefrence, 10);
    WebElement element = wait.until(ExpectedConditions.visibilityOfElementLocated(element0));
    element.click();
    

    这将等待 up 到 10 秒以使元素可见。您还有更多 ExpectedConditions 可供选择。

    【讨论】:

      【解决方案2】:

      在 findElement 之后使用 sleep 也会导致无意义的暂停,因为 findElemen 将使用定义的超时 https://www.selenium.dev/selenium/docs/api/java/org/openqa/selenium/WebDriver.Timeouts.html

      您可以为等待元素增加隐式等待超时。

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

      【讨论】:

        【解决方案3】:

        Thread.Sleep()

        使用Thread.Sleep() 暂停执行会导致当前正在执行的线程在指定的时间段内暂停执行。这是一种使处理器时间可用于应用程序的其他线程或可能在同一系统上运行的其他应用程序的有效方法。但是,不能保证这些睡眠时间是精确的,因为它们受到底层 提供的设施的限制。睡眠周期也可以通过中断终止。底线是,你不能假设调用 sleep 会在指定的时间段内暂停线程。


        隐式等待

        使用Selenium 时,您可以将sleep 替换为implicitlyWait。通过诱导implicitlyWait驱动程序 实例将轮询DOM Tree,直到在配置的时间内找到元素,然后在抛出NoSuchElementException 之前寻找一个或多个元素。

        • 例子:

          • Python

            driver.implicitly_wait(10)
            
          • Java

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

            driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(10);
            

        显式等待

        但是,更好的方法是将 sleep 替换为 ExplicitWait,它将驱动程序实例配置为等待满足特定条件,然后再继续执行下一行代码。

        • 例子:

          • Python

            WebDriverWait(driver, 20).until(EC.presence_of_element_located((By.CSS_SELECTOR, "element_css")))
            
          • Java

            new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("element_css")));
            
          • 点网

            new WebDriverWait(driver, TimeSpan.FromSeconds(10)).Until(ExpectedConditions.ElementIsVisible(By.CssSelector("element_css")))
            

        【讨论】:

          猜你喜欢
          • 2012-03-23
          • 2012-09-17
          • 1970-01-01
          • 2011-04-04
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-08-13
          • 2017-03-12
          相关资源
          最近更新 更多