Selenium 4以后,再不相见的API

摘要:
硒4的最新进展在硒4前线公告中提到。随着Selenium 4各种功能的增强,最新版本还包括一些旧API的更改和启用。如果您要从Selenium 3升级到Selenium 4,最好注意这些更新。本文中列出的API似乎正在向所有Selenium用户告别!在Selenium 3中,我们在使用RemoteWebDriver时广泛使用DesiredCapabilities。这是设置浏览器功能的必要步骤,以便可以在基于云的Seleniumbird上运行测试。当使用Selenium 4时,我们需要设置必要的测试要求,并将对象传递给Driver构造函数。

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官方合作媒体。


免责声明:文章转载自《Selenium 4以后,再不相见的API》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇Hadoop实战实例IOS计算文字高度下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

第五章 Gateway--服务网关

欧克 ,我接着上篇第四章 Sentinel–服务容错,继续写下去 开始网关之旅 5.1网关简介 大家都都知道在微服务架构中,一个系统会被拆分为很多个微服务。那么作为客户端要如何去调用这么多的微服务呢?如果没有网关的存在,我们只能在客户端记录每个微服务的地址,然后分别去用。 这样的架构,会存在着诸多的问题: 客户端多次请求不同的微服务,增加客户端代码...

PHPDoc/PHPDocumentor生成API文档

PHPDocumentor是一个用PHP写的强大的文档自动生成工具,对于有规范注释的php程序,能够快速生成具有结构清晰、相互参照、索引等功能的API文档。旧版本是PHPDoc,PHPDoc是PEAR下面的一个非常优秀的模块,类似于Javadoc。从1.3.0开始,更名为phpDocumentor,新版本新加了对php5语法的支持,同时,可以通过在客户端浏...

(包含项目)selenium操作对象的text方法和智能等待时间

基础知识 1  js:JavaScript缩写     json:JavaScript的一种数据格式 2  浏览器的原理:把 html+css+js 下载到本地然后再进行渲染。即看到网页这个过程,实际上是浏览器把代码下载下来,然后浏览器来解释这个代码,变成界面的过程。 3  查看网页源代码:就是别人服务器发送到浏览器的原封不动的代码。这个代码没有被浏览器...

selenium介绍

Selenium介绍 from selenium import webdriver # 生成浏览器服务 driver = webdriver.Chrome() # 向服务发送HTTP请求 post方式 将参数携带过去 # 下面这个不是用get方式请求,是selenium封装的一个get函数 名字叫get driver.get('http://ui.imd...

cookie,session原理,以及如何使用chrome查看。

首先,先补充下chrome浏览器的使用。 1.1、php源码: <?php $cookieDomain = '.elf.com'; setcookie('elf', 'im elf cookie', time()+300, '/', $cookieDomain); setcookie('aaa', 'aaaa', time()+10); 1.2...

循序渐进学.Net Core Web Api开发系列【8】:访问数据库(基本功能)

系列目录 循序渐进学.Net Core Web Api开发系列目录 本系列涉及到的源码下载地址:https://github.com/seabluescn/Blog_WebApi 一、概述 本篇讨论如何连接数据库,包括连接SQL Server 和 连接MySQL,然后做一些基本的数据操作。 二、连接SQL Server 首先通过NuGet添加相关的包:...