如何控制 Chromedriver 打开窗口的大小?

seleniumautomation testingtesting tools更新于 2026/2/5 6:22:17

我们可以在 Selenium 中控制 Chromedriver 的打开窗口大小。这借助 ChromeOptions 类来实现。我们需要创建一个该类的对象,并在其上应用 addArguments 方法。

然后将 window-size=x, y 作为参数传递给该方法。x 和 y 是窗口的尺寸。接下来,我们需要使用 DesiredCapabilities 类将此选项应用于 Chrome 浏览器。最后,此信息将发送到驱动程序对象。

语法

ChromeOptions op = new ChromeOptions();
op.addArguments("window-size=500,250");
DesiredCapabilities c = DesiredCapabilities.chrome();
c.setCapability(ChromeOptions.CAPABILITY, op);
WebDriver d = new ChromeDriver(op);

示例

代码实现。

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import java.util.concurrent.TimeUnit;
public class ChromeWindowSize{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver", "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
      //ChromeOptions 对象
      ChromeOptions op = new ChromeOptions();
      //设置窗口大小
      op.addArguments("window-size=500,250");
      //设置浏览器能力
      DesiredCapabilities c = DesiredCapabilities.chrome();
      c.setCapability(ChromeOptions.CAPABILITY, op);
      WebDriver driver = new ChromeDriver(op);
      driver.get("https://www.tutorialspoint.com/index.htm");
      // 获取窗口大小
      System.out.println
      ("Chrome 浏览器大小: " + driver.manage().window().getSize());
   }
}

输出

浏览器窗口 −


相关文章