显式等待执行什么操作?

javascriptprogramming更新于 2026/1/28 11:56:17

显式等待应用于网页中的特定元素。它将暂停执行,直到条件得到满足。显式等待也是动态的,因为如果等待时间为十五秒,并且在此指定时间之前满足条件(例如等待元素可点击、可见或可选等),则控件将移至下一步。

显式等待更具可定制性,因为我们可以根据条件进行设置。下面列出了一些显式等待的预期条件 −

  • textToBePresentInElement()

    语法

    w.until(ExpectedConditions.textToBePresentInElement(By.id(“<<id expression>>“), “Tutorialspoint”));
    
  • textToBeClickable()

    语法

    w.until(ExpectedConditions.textToBeClickable(By.id(“<<id expression>>“)));
    
  • alertisPresent()

    语法

    w.until(ExpectedConditions.alertisPresent())= null);
    
  • frameToBeAvailableAndSwitchToIt()

    语法

    w.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.id(“<<frame id >>“)));
    

显式在实现方面比较复杂,但是它不影响执行速度,并且适用于页面上的特定元素。

在显式等待中,一旦超过最大时间,就会抛出 ElementNotVisibleException。

示例

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 org.openqa.selenium.support.ui.Wait;
public class Explictwt {
   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);
      //单击 Coding Ground 链接
      driver.findElement(By.xpath("//span[text()=’Coding Ground’]")).click();
      // 显式等待声明
      WebDriverWait w = new WebDriverWait(driver,10);
      // 使用 textToBePresentInElement 方法等待的条件
      w.until(ExpectedConditions.textToBePresentInElement(By.xpath("//img[@title=’Whiteboard’]"),”          Whiteboard”));
      driver.quit();
   }
}

有用资源