在 Selenium WebDriver 测试中,使用 Java 实现 waitForVisible/waitForElementPresent 的等效方法是什么?

seleniumautomation testingtesting tools更新于 2026/1/23 20:07:17

Selenium WebDriver 中有 waitForVisible/waitForElementPresent 的等效方法。它们是 Selenium 同步概念的一部分。

同步中的等待分为隐式等待和显式等待。

隐式等待是指在 WebDriver 中对所有元素应用指定的等待时间。如果超过此时间,某个元素仍然不可用,则会抛出一个期望值。

语法

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

示例

隐式等待的代码实现

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
public class ImplctWait{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver",
         "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      //隐式等待 5 秒
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      //URL 启动
      driver.get("https://www.tutorialspoint.com/index.htm");
      // 识别元素
      WebElement m = driver.findElement(By.tagName("h4"));
      System.out.println("Element text is: " + m.getText());
      driver.quit();
   }
}

输出

显式等待是指在指定的时间内,等待 Web 驱动程序满足元素的预期条件。如果超过此时间,且未满足预期条件,则会抛出异常。

waitForVisible 方法的等效方法可以是显式等待中 visibilityOfElementLocated 预期条件。同样,waitForElementPresent 方法的等效方法可以是 presenceOfElementLocated 预期条件。

语法

WebDriverWait w= (new WebDriverWait(driver,5 ));
w.until(ExpectedConditions.presenceOfElementLocated(By.id("txt")));
w.until(ExpectedConditions.visibilityOfElementLocated (By.name("nam-txt")));

示例

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class ExplicitWt{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver",
         "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      //启动 URL
      driver.get("https://www.tutorialspoint.com/index.htm");
      //显式等待条件 - presenceOfElementLocated
      WebDriverWait w= (new WebDriverWait(driver, 7));
      w.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//*[text()='Library']")));
      WebElement m = driver.findElement(By.xpath("//*[text()='Library']"));
      m.click();
      //显式等待条件 - visibilityOfElementLocated
      w.until(ExpectedConditions.visibilityOfElementLocated (By.linkText("Subscribe to Premium")));
      WebElement n = driver.findElement(By.linkText("Subscribe to Premium"));
      String s = n.getText();
      System.out.println("Text is: " + s);
      driver.quit();
   }
}

输出


相关文章