如何在 Selenium WebDriver 中设置浏览器宽度和高度?


我们可以在 Selenium webdriver 中设置浏览器宽度和高度。有多种方法可以实现这一点。每当启动应用程序时,它都会以其默认浏览器大小打开。

我们可以借助 Java 中的 Dimension 类调整浏览器大小。我们创建 Dimension 类的对象,并将浏览器所需的宽度和高度作为参数传递给该类。最后,我们将 Dimension 类的对象作为参数传递给 setSize 方法。

语法

Dimension dem = new Dimension(750,450);
driver.manage().window().setSize(dem);

我们还可以借助 Chrome 选项设置浏览器宽度和高度。我们必须创建 ChromeOptions 类的对象,并对其应用 addArguments。参数 window-size 设置了浏览器的高度和宽度值,作为参数传递给该方法。此知识通过 DesiredCapabilities 类传递给浏览器调用方法。

语法

ChromeOptions options = new ChromeOptions();
options.addArguments("window-size=750,450");

DesiredCapabilities capabilities = DesiredCapabilities.chrome();
capabilities.setCapability(ChromeOptions.CAPABILITY, options);
WebDriver driver = new ChromeDriver(capabilities);

示例

使用 Dimension 类进行代码实现。

import org.openqa.selenium.Dimension;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class BrowserResize{
   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://tutorialspoint.com/tutor_connect/index.php";
      driver.get(url);
      // Dimension class with browser width and height value passed
      Dimension dem = new Dimension(750,450);
      // passing the Dimension object as an argument to setSize method
      driver.manage().window().setSize(dem);

使用 Chrome 选项进行实现。

import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class BrowserResizeOptions{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver", "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
      // ChromeOptions class with addArguments method
      ChromeOptions options = new ChromeOptions();
      options.addArguments("window-size=750,450");
      DesiredCapabilities capabilities = DesiredCapabilities.chrome();
      capabilities.setCapability(ChromeOptions.CAPABILITY, options);
      WebDriver driver = new ChromeDriver(capabilities);
      String url = "https://tutorialspoint.com/tutor_connect/index.php";
      driver.get(url);
   }
}

更新于: 2020年10月26日

4K+ 浏览量

开启你的 职业生涯

通过完成课程获得认证

开始学习
广告

© . All rights reserved.