selenium-java等待方式

简单的案例

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.chrome.ChromeOptions;

public class seleniumWait {
    public static void main(String[] args) {
        System.setProperty("webdriver.chrome.driver", "/usr/local/bin/chromedriver");
        ChromeOptions options = new ChromeOptions();
//        options.addArguments("--headless"); // 如果不需要浏览器窗口,可以加上这行
        WebDriver driver = new ChromeDriver(options);
        // 1.打开百度搜索
        driver.get("https://www.baidu.com/");

        // 2.定位搜索框
        WebElement input = driver.findElement(By.name("wd"));

        // 3。在搜索框输入对应信息
        input.sendKeys("开思通智网");
        
        //点击百度一下
        driver.findElement(By.id("su")).click();
    }
}

1. 隐式等待(Implicit Wait)

概念:

隐式等待是告诉 WebDriver 等待一定的时间,如果在这段时间内元素仍然无法找到,则抛出 NoSuchElementException。隐式等待在设置之后会在整个 WebDriver 实例的生命周期内起作用。

使用场景:

隐式等待适用于希望 WebDriver 在寻找任何元素时都等待一段时间。这种等待机制不需要频繁设置,可以用于处理网络延迟或加载较慢的页面。

代码表示

driver.manage.timeouts.implicitlyWait(long time, TimeUtil unit);

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;

public class ImplicitWaitExample {
    public static void main(String[] args) {
        WebDriver driver = new ChromeDriver();
        // 设置隐式等待时间为10秒
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        driver.get("https://example.com");
        
        // 尝试查找元素
        WebElement element = driver.findElement(By.id("elementId"));
        
        // 你的测试代码
        driver.quit();
    }
}

2. 显式等待(Explicit Wait)

概念:

显式等待用于在指定的条件下等待特定元素。WebDriverWait 和 ExpectedConditions 是显式等待的两个主要组成部分。WebDriverWait 在设定的超时时间内每隔一段时间检查一次条件是否满足,如果条件在超时时间内未满足,则抛出 TimeoutException。

使用场景:

显式等待适用于需要等待特定条件(如元素可见、元素可点击等)的场景。与隐式等待相比,显式等待更为灵活和精确。

代码示例:

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 ExplicitWaitExample {
    public static void main(String[] args) {
        WebDriver driver = new ChromeDriver();
        driver.get("https://example.com");
        
        // 设置显式等待
        WebDriverWait wait = new WebDriverWait(driver, 10);
        // 等待元素可见
        WebElement element = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("elementId")));
        
        // 你的测试代码
        driver.quit();
    }
}

常用预定义条件

  • visibilityOfElementLocated(By locator): 等待元素可见
  • elementToBeClickable(By locator): 等待元素可点击
  • presenceOfElementLocated(By locator): 等待元素存在于DOM中
  • titleContains(String title): 等待页面标题包含特定字符串
  • urlContains(String fraction): 等待URL包含特定字符串

使用步骤

  1. 创建WebDriverWait对象,设定最长等待时间。
  2. 使用ExpectedConditions定义具体的等待条件。
  3. 使用until方法将等待条件传递给WebDriverWait对象。

3. Fluent 等待(Fluent Wait)

概念:

Fluent 等待是显式等待的增强版,允许用户定义等待的频率和忽略的异常类型。它提供更高的灵活性,可以在等待过程中每隔一段时间检查一次条件。

使用场景:

Fluent 等待适用于需要在等待过程中进行多次检查的复杂场景,例如等待页面动态内容加载。

代码示例:

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.FluentWait;

import java.time.Duration;
import java.util.NoSuchElementException;
import java.util.function.Function;

public class FluentWaitExample {
    public static void main(String[] args) {
        WebDriver driver = new ChromeDriver();
        driver.get("https://example.com");
        
        // 设置 Fluent 等待
        FluentWait<WebDriver> wait = new FluentWait<>(driver)
            .withTimeout(Duration.ofSeconds(10)) // 最大等待时间
            .pollingEvery(Duration.ofSeconds(1)) // 每隔1秒检查一次
            .ignoring(NoSuchElementException.class); // 忽略 NoSuchElementException
        
        // 等待元素出现
        WebElement element = wait.until(new Function<WebDriver, WebElement>() {
            public WebElement apply(WebDriver driver) {
                return driver.findElement(By.id("elementId"));
            }
        });
        
        // 你的测试代码
        driver.quit();
    }
}

4. 线程睡眠(Thread.sleep)

概念:

线程睡眠是强制暂停当前线程执行一段时间。虽然简单易用,但不推荐在自动化测试中频繁使用,因为它会使测试变得不稳定和缓慢。

使用场景:

线程睡眠仅在调试或其他等待机制无法满足需求的情况下使用。

代码示例:

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class ThreadSleepExample {
    public static void main(String[] args) throws InterruptedException {
        WebDriver driver = new ChromeDriver();
        driver.get("https://example.com");
        
        // 强制等待5秒
        Thread.sleep(5000);
        
        // 你的测试代码
        driver.quit();
    }
}

总结

隐式等待:适用于全局等待,简化代码,但不适合特定条件。

显式等待:灵活且精确,适用于特定条件的等待。

Fluent 等待:增强版显式等待,适用于复杂场景。

线程睡眠:简单但不推荐,仅在特殊情况下使用。

转载自开思通智网:https://w3.opensnn.com/os/article/10001329

  • 4
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值