隐式等待有何作用?

java programming object oriented programmingprogramming更新于 2026/1/28 11:24:17

隐式等待是指我们执行过程中每个测试步骤的默认等待时间。因此,如果我们将隐式等待时间设置为 10 秒,则每个测试步骤都会等待该时间以执行操作,然后转至下一步。

隐式等待是一种动态等待,这意味着如果等待时间为 10 秒,并且要执行下一步操作的 Web 元素在第五秒可用,则控制权将立即转至下一个测试步骤,而不是等待整整 10 秒。

但是,如果该元素直到第十秒才可用,则会引发异常。隐式等待使用起来简单易行,但也存在一些缺点,例如:−

  • 会减慢测试执行时间。

  • 无法捕获代码中的性能错误。

隐式等待会应用于测试执行中涉及的所有元素,并被视为全局等待。

示例

import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
import java.util.List;
public class Implictwt {
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver", "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      String url = "https://www.tutorialspoint.com/index.htm";
      driver.get(url);
      //对每个元素应用隐式等待时间(以秒为单位)
      driver.manage().timeouts().implicitlyWait(12, TimeUnit.SECONDS);
      //使用 id 标签名 属性组合进行 css 表达式
      driver.findElement(By.cssSelector("input[name=’search’]")).
      sendKeys("Selenium");
      driver.close();
   }
}

相关文章