zoukankan      html  css  js  c++  java
  • Selenium 4以后,再不相见的API

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


  • 相关阅读:
    一种简洁明了的权限管理系统
    css小技巧(1)
    多功能旋转木马轮播实例
    jquery双向列表选择器select版
    jquery双向列表选择器DIV模拟版
    单击页面任何地方关闭隐藏层
    用户登录体验之密码框设计
    扁平化设计的美感
    分析网站的用户行为
    app的架构和导航设计
  • 原文地址:https://www.cnblogs.com/FunTester/p/15099644.html
Copyright © 2011-2022 走看看