如何在 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.tw/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.tw/tutor_connect/index.php";
      driver.get(url);
   }
}

更新於: 2020年10月26日

4K+ 瀏覽量

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.