专栏文章 Selenium 4 以后,再不相见的 API

FunTester · 2021年08月04日 · 1137 次阅读

Selenium4 前线快报中提到了 Selenium 4 的最新进展,伴随着 Selenium 4 各种功能的增强,最近的版本中也包含了一些旧 API 的更改和启用。如果你准备从 Selenium 3 升级到 Selenium 4,那么最好留意这些更新。

文中所列的 API,看样子要跟所有 Seleniumer 说再见了!

弃用 DesiredCapabilities

在 Selenium 3 中,我们在使用 RemoteWebDriver 时广泛使用了 DesiredCapabilities。这是设置浏览器功能所必需的步骤,以便测试可以在基于云的 Selenium gird 上运行。但是在 Selenium 4 中,我们告别了 DesiredCapabilities。

Capabilities 对象现在替换为 Options,我们需要创建一个 Options 对象来使用 Driver 类。使用 Selenium 4 时,我们需要设置必要的测试要求(即浏览器和操作系统组合)并将对象传递给 Driver 构造函数。

下面演示一下不同浏览器的案例。

Chrome

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

import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Parameters;
import org.openqa.selenium.WebDriver;
import java.net.MalformedURLException;
import org.openqa.selenium.remote.RemoteWebDriver;

public void testSetUp() throws Exception
{
        ChromeOptions options = new ChromeOptions();
        options.setAcceptInsecureCerts(true);

        options.setCapability("build", "Testing Chrome Options [Selenium 4]");
        options.setCapability("name", "Testing Chrome Options [Selenium 4]");
        options.setCapability("platformName", "Windows 10");
        options.setCapability("browserName", "Chrome");
        options.setCapability("browserVersion", "latest");

        try {
            driver = new RemoteWebDriver(new URL("http://" + username + ":" + access_key + "@hub.lambdatest.com/wd/hub"), ((Capabilities) options));
        } catch (MalformedURLException e) {
            System.out.println("Invalid grid URL");
        }
        driver.get("https://www.lambdatest.com");
}

本地

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

import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Parameters;
import org.openqa.selenium.WebDriver;
import java.net.MalformedURLException;

public void testSetUp()
{
        ChromeOptions options = new ChromeOptions();
        options.setAcceptInsecureCerts(true);
        driver.get("https://www.lambdatest.com");
}

FirefoxDriver

import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;

import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Parameters;
import org.openqa.selenium.WebDriver;
import java.net.MalformedURLException;
import org.openqa.selenium.remote.RemoteWebDriver;


public void testSetUp() throws Exception
{
        FirefoxOptions options = new FirefoxOptions();
        options.setAcceptInsecureCerts(true);

        options.setCapability("build", "Testing Firefox Options [Selenium 4]");
        options.setCapability("name", "Testing Firefox Options [Selenium 4]");
        options.setCapability("platformName", "Windows 10");
        options.setCapability("browserName", "Firefox");
        options.setCapability("browserVersion", "68.0");

        try {
            driver = new RemoteWebDriver(new URL("http://" + username + ":" + access_key + "@hub.lambdatest.com/wd/hub"), ((Capabilities) options));
        } catch (MalformedURLException e) {
            System.out.println("Invalid grid URL");
        }
        driver.get("https://www.lambdatest.com");
}

本地

import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;

import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Parameters;
import org.openqa.selenium.WebDriver;
import java.net.MalformedURLException;

public void testSetUp()
{
        FirefoxOptions options = new FirefoxOptions();
        options.setAcceptInsecureCerts(true);
        driver.get("https://www.lambdatest.com");

}

IEDriver

省略,内容基本同上。

SafariDriver

省略,内容基本同上。

FindsBy

RemoteWebDriver 类实现的 FindElement 和 FindElements 方法分别用于定位单个 WebElement 和 WebElement 列表。FindsBy 接口是 org.openqa.selenium.internal 包的一部分,在 Selenium 4 中已弃用。

这些更改是 Selenium 框架的内部更改,Selenium 用户可以继续使用 Selenium 3 中使用的 FindElement(By by) 和 FindElements(By by)。

使用方式如下:

WebElement eid = driver.findElement(By.id("email"));
WebElement pswd = driver.findElement(By.name("password"));
WebElement sbmtBtn = driver.findElement(By.xpath("//input[@value="submit"]");
List<webelement> elem_signUpForm = driver.findElements(By.className("cell-body-textinput"));
List<webelement> elem_address = driver.findElements(By.name("Address"));

Actions 类的新功能

Selenium 中的 Actions 类提供了多种方法来对 DOM 中存在的 WebElements 执行单个操作或操作组合。操作分为鼠标操作(例如单击、双击等)和键盘操作(例如 keyUp、keyDown、sendKeys)是两大类操作。

我们演示从 Selenium 3 移植到 Selenium 4。

在 Selenium 4 中,新方法被添加到 Actions 类中,它取代了 org.openqa.selenium.interactions 包下的类。

作击

click(WebElement) 是添加到 Actions 类的新方法,它替代了 moveToElement(onElement).click() 方法。

与 Selenium 4 之前 alpha 版本中的方法一样,click(WebElement) 用于单击 Web 元素。

public void FunTester() throws InterruptedException
{
    driver.navigate().to("https://www.amazon.in/");
    driver.manage().window().maximize();

    try {
        Actions action = new Actions(driver);

        WebElement elementToType = driver.findElement(By.cssSelector("#twotabsearchtextbox"));

        action.sendKeys(elementToType, "iphone").build().perform();

        WebElement elementToClick = driver.findElement(By.xpath("//input[@value='Go']"));

        Thread.sleep(5000);

        action.click(elementToClick).build().perform();

        Thread.sleep(5000);

        assertEquals(driver.getTitle(), "Amazon.in : iphone");
    } catch (Exception e) {
        System.out.println(e.getMessage());
    }
}

双击和右击

在 Selenium 4 中,用于双击 WebElement 的方法 moveToElement(element).doubleClick() 被替换为 doubleClick(WebElement) 方法。

用于右键单击的方法 moveToElement(onElement).contextClick() 现在已替换为 Selenium 4 中的 contextClick(WebElement) 方法。

下面是示例:

public void FunTester() throws InterruptedException 
{
    driver.navigate().to("https://www.amazon.in/");
    driver.manage().window().maximize();

    try {
        Actions action = new Actions(driver);

        WebElement element = driver.findElement(By.xpath("//a[.='Mobiles']"));

        action.doubleClick(element).build().perform();

        Thread.sleep(5000);
        assertEquals(driver.getTitle(), "Mobile Phones: Buy New Mobiles Online at Best Prices in India | Buy Cell Phones Online - Amazon.in");

        driver.manage().timeouts().pageLoadTimeout(10, TimeUnit.SECONDS);
        action.contextClick().build().perform();
    } catch (Exception e) {
        System.out.println(e.getMessage());
    }
}

拖拽

用于单击 WebElement 而不执行 Release 操作的方法 moveToElement(Element).clickAndHold() 替换为 clickAndHold(WebElement)。

用于释放按下的鼠标按钮的 release() 方法是 org.openqa.selenium.interactions.ButtonReleaseAction 类的一部分。在 Selenium 4 中,该方法是 Actions 类的一部分。

下面是示例:

public void test_LambdaTest_click_hold_demo() throws InterruptedException
{
    driver.navigate().to("https://selenium08.blogspot.com/2020/01/click-and-hold.html");
    driver.manage().timeouts().pageLoadTimeout(10, TimeUnit.SECONDS);
    driver.manage().window().maximize();

    try {
        Actions action = new Actions(driver);

        WebElement elem_source = driver.findElement(By.xpath("//li[text()= 'C']"));
        WebElement elem_destination = driver.findElement(By.xpath("//li[text()= 'A']"));

        action.clickAndHold(elem_source).release(elem_destination).build().perform();
        Thread.sleep(2000);
    } catch (Exception e) {
        System.out.println(e.getMessage());
    }
}

FluentWait

之前介绍过Selenium 等待:sleep、隐式、显式和 Fluent。Selenium 中的 FluentWait 用于在元素可见或可点击所需的时间不确定时执行 Selenium 等待。

如 FluentWait in Selenium 示例(使用 Selenium 3)所示,withTimeOut() 方法采用两个参数——int 和 TimeUnit。
如下演示 Demo 中,使用 withTimeOut() 方法两个参数来控制等待总时间。

.withTimeout(60, SECONDS)

pollingEvery() 方法有两个参数控制轮询的频率。

.pollingEvery(2, SECONDS)

Selenium 3

Wait<webdriver> fluentWait = new FluentWait<webdriver>(driver)
       .withTimeout(60, SECONDS) 
       .pollingEvery(2, SECONDS) 
       .ignoring(NoSuchElementException.class); 

    WebElement foo = fluentWait.until(new Function<webdriver, webelement="">()
    {
        public WebElement apply(WebDriver driver)  
        {  
            return driver.findElement(By.id("foo"));
        }
    }
    );

Selenium 4

在 Selenium 4 中,作为 FluentWait 类一部分的 withTimeout() 和 pollingEvery() 方法已被修改。所述 pollingEvery() 方法仅接受一个参数。Duration 可以是 Seconds、MilliSeconds、NanoSeconds、Hours、Days 等。在类似的行中,withTimeOut() 方法也只采用一个参数。

示例 – Selenium 4 中的 FluentWait

Wait<webdriver> fluentWait = new FluentWait<webdriver>(driver)
       .withTimeout(Duration.ofSeconds(120))
       .pollingEvery(Duration.ofMillis(2000))
       .ignoring(NoSuchElementException.class); 

    WebElement foo = fluentWait.until(new Function<webdriver, webelement="">()
    {
        public WebElement apply(WebDriver driver)        {  
            return driver.findElement(By.id("foo"));
        }
    }
    );

Have Fun ~ Tester !

FunTester,一群有趣的灵魂,腾讯云&Boss 认证作者,GDevOps 官方合作媒体。


如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!
暂无回复。
需要 登录 后方可回复, 如果你还没有账号请点击这里 注册