ITPub博客

首页 > 应用开发 > IT综合 > Java Selenium控制浏览器窗口尺寸的方法与实践

Java Selenium控制浏览器窗口尺寸的方法与实践

投稿 IT综合 作者:bhluo 时间:2025-12-18 16:45:59 0 删除 编辑

# Java Selenium控制浏览器窗口尺寸的方法与实践


## 引言:浏览器窗口管理的重要性


在现代Web自动化测试和爬虫开发中,精确控制浏览器窗口尺寸已成为一项关键技能。不同的屏幕分辨率、响应式设计测试以及特定场景下的界面验证,都需要对浏览器窗口进行精细化管理。Selenium作为广泛使用的浏览器自动化工具,提供了丰富的API来控制窗口尺寸。本文将深入探讨如何使用Java Selenium实现浏览器窗口大小的动态调整与优化。


## 环境配置与基础设置


### 项目依赖配置


首先,在Maven项目中添加必要的依赖:


```xml

<dependencies>

    <!-- Selenium Java依赖 -->

    <dependency>

        <groupId>org.seleniumhq.selenium</groupId>

        <artifactId>selenium-java</artifactId>

        <version>4.15.0</version>

    </dependency>

    

    <!-- WebDriverManager用于自动管理浏览器驱动 -->

    <dependency>

        <groupId>io.github.bonigarcia</groupId>

        <artifactId>webdrivermanager</artifactId>

        <version>5.6.3</version>

    </dependency>

    

    <!-- 测试框架 -->

    <dependency>

        <groupId>org.junit.jupiter</groupId>

        <artifactId>junit-jupiter</artifactId>

        <version>5.10.1</version>

        <scope>test</scope>

    </dependency>

</dependencies>

```


### 基础WebDriver初始化


```java

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;

import org.openqa.selenium.chrome.ChromeOptions;

import io.github.bonigarcia.wdm.WebDriverManager;


public class BrowserWindowManager {

    

    private WebDriver driver;

    

    /**

     * 初始化Chrome浏览器驱动

     */

    public void initializeChromeDriver() {

        // 自动下载和管理ChromeDriver

        WebDriverManager.chromedriver().setup();

        

        // 配置浏览器选项

        ChromeOptions options = new ChromeOptions();

        

        // 添加常用选项

        options.addArguments("--disable-notifications"); // 禁用通知

        options.addArguments("--disable-infobars"); // 禁用信息栏

        options.addArguments("--disable-extensions"); // 禁用扩展

        

        // 设置默认下载目录(可选)

        // HashMap<String, Object> prefs = new HashMap<>();

        // prefs.put("download.default_directory", "/path/to/download");

        // options.setExperimentalOption("prefs", prefs);

        

        // 创建WebDriver实例

        driver = new ChromeDriver(options);

    }

    

    /**

     * 初始化Firefox浏览器驱动

     */

    public void initializeFirefoxDriver() {

        WebDriverManager.firefoxdriver().setup();

        // FirefoxOptions options = new FirefoxOptions();

        // driver = new FirefoxDriver(options);

    }

    

    /**

     * 获取当前WebDriver实例

     */

    public WebDriver getDriver() {

        if (driver == null) {

            throw new IllegalStateException("WebDriver未初始化,请先调用初始化方法");

        }

        return driver;

    }

    

    /**

     * 关闭浏览器和驱动

     */

    public void quitDriver() {

        if (driver != null) {

            driver.quit();

            driver = null;

        }

    }

}

```


## 窗口尺寸控制基础方法


### 获取和设置窗口尺寸


```java

import org.openqa.selenium.Dimension;

import org.openqa.selenium.Point;

import org.openqa.selenium.WebDriver;


public class WindowSizeController {

    

    private final WebDriver driver;

    

    public WindowSizeController(WebDriver driver) {

        this.driver = driver;

    }

    

    /**

     * 获取当前窗口尺寸

     */

    public Dimension getCurrentWindowSize() {

        return driver.manage().window().getSize();

    }

    

    /**

     * 设置窗口尺寸

     * @param width 宽度(像素)

     * @param height 高度(像素)

     */

    public void setWindowSize(int width, int height) {

        Dimension targetSize = new Dimension(width, height);

        driver.manage().window().setSize(targetSize);

        

        System.out.println("窗口尺寸设置为: " + width + "x" + height);

        Dimension actualSize = getCurrentWindowSize();

        System.out.println("实际窗口尺寸: " + actualSize.getWidth() + "x" + actualSize.getHeight());

    }

    

    /**

     * 设置窗口为最大尺寸

     */

    public void maximizeWindow() {

        driver.manage().window().maximize();

        System.out.println("窗口已最大化");

        

        Dimension size = getCurrentWindowSize();

        System.out.println("最大化后尺寸: " + size.getWidth() + "x" + size.getHeight());

    }

    

    /**

     * 设置窗口为最小尺寸

     */

    public void minimizeWindow() {

        driver.manage().window().minimize();

        System.out.println("窗口已最小化");

    }

    

    /**

     * 设置窗口为全屏模式

     */

    public void fullscreenWindow() {

        driver.manage().window().fullscreen();

        System.out.println("窗口已全屏");

        

        Dimension size = getCurrentWindowSize();

        System.out.println("全屏后尺寸: " + size.getWidth() + "x" + size.getHeight());

    }

    

    /**

     * 获取窗口位置

     */

    public Point getWindowPosition() {

        return driver.manage().window().getPosition();

    }

    

    /**

     * 设置窗口位置

     * @param x 横坐标

     * @param y 纵坐标

     */

    public void setWindowPosition(int x, int y) {

        Point targetPosition = new Point(x, y);

        driver.manage().window().setPosition(targetPosition);

        

        System.out.println("窗口位置设置为: (" + x + ", " + y + ")");

    }

    

    /**

     * 同时设置窗口位置和尺寸

     */

    public void setWindowRect(int x, int y, int width, int height) {

        setWindowPosition(x, y);

        setWindowSize(width, height);

    }

}

```


### 常用分辨率预设


```java

import java.util.HashMap;

import java.util.Map;


public class StandardResolutions {

    

    /**

     * 常见设备分辨率预设

     */

    public enum DeviceResolution {

        // 桌面端

        DESKTOP_1920x1080(1920, 1080, "桌面全高清"),

        DESKTOP_1366x768(1366, 768, "桌面标准"),

        DESKTOP_1536x864(1536, 864, "桌面常见"),

        

        // 笔记本电脑

        LAPTOP_1440x900(1440, 900, "笔记本常见"),

        LAPTOP_1280x800(1280, 800, "笔记本小屏"),

        

        // 平板设备

        TABLET_1024x768(1024, 768, "iPad标准"),

        TABLET_1280x720(1280, 720, "平板高清"),

        

        // 移动设备

        MOBILE_375x667(375, 667, "iPhone 6/7/8"),

        MOBILE_414x896(414, 896, "iPhone XR/11"),

        MOBILE_360x640(360, 640, "Android常见"),

        

        // 响应式断点

        RESPONSIVE_SM(640, 480, "小屏幕"),

        RESPONSIVE_MD(768, 1024, "中等屏幕"),

        RESPONSIVE_LG(1024, 768, "大屏幕"),

        RESPONSIVE_XL(1280, 800, "超大屏幕");

        

        private final int width;

        private final int height;

        private final String description;

        

        DeviceResolution(int width, int height, String description) {

            this.width = width;

            this.height = height;

            this.description = description;

        }

        

        public int getWidth() { return width; }

        public int getHeight() { return height; }

        public String getDescription() { return description; }

    }

    

    private final WebDriver driver;

    

    public StandardResolutions(WebDriver driver) {

        this.driver = driver;

    }

    

    /**

     * 设置为特定设备分辨率

     */

    public void setToDeviceResolution(DeviceResolution resolution) {

        WindowSizeController controller = new WindowSizeController(driver);

        controller.setWindowSize(resolution.getWidth(), resolution.getHeight());

        

        System.out.println("设置为设备分辨率: " + resolution.getDescription() +

                         " (" + resolution.getWidth() + "x" + resolution.getHeight() + ")");

    }

    

    /**

     * 测试多个分辨率

     */

    public void testMultipleResolutions() {

        DeviceResolution[] testResolutions = {

            DeviceResolution.MOBILE_375x667,

            DeviceResolution.TABLET_1024x768,

            DeviceResolution.DESKTOP_1366x768,

            DeviceResolution.DESKTOP_1920x1080

        };

        

        for (DeviceResolution resolution : testResolutions) {

            setToDeviceResolution(resolution);

            // 可以在这里添加页面截图或验证逻辑

            try {

                Thread.sleep(1000); // 等待1秒观察效果

            } catch (InterruptedException e) {

                Thread.currentThread().interrupt();

            }

        }

    }

    

    /**

     * 获取所有分辨率的信息

     */

    public Map<String, String> getAllResolutionsInfo() {

        Map<String, String> info = new HashMap<>();

        

        for (DeviceResolution resolution : DeviceResolution.values()) {

            String key = resolution.getWidth() + "x" + resolution.getHeight();

            String value = resolution.getDescription() + " - " + resolution.name();

            info.put(key, value);

        }

        

        return info;

    }

}

```


## 高级窗口管理技巧


### 多窗口管理与切换


```java

import org.openqa.selenium.WebDriver;

import java.util.Set;

import java.util.List;

import java.util.ArrayList;


public class MultiWindowManager {

    

    private final WebDriver driver;

    private String mainWindowHandle;

    

    public MultiWindowManager(WebDriver driver) {

        this.driver = driver;

        this.mainWindowHandle = driver.getWindowHandle();

    }

    

    /**

     * 获取所有窗口句柄

     */

    public Set<String> getAllWindowHandles() {

        return driver.getWindowHandles();

    }

    

    /**

     * 切换到新窗口

     */

    public void switchToNewWindow() {

        Set<String> handles = getAllWindowHandles();

        

        for (String handle : handles) {

            if (!handle.equals(mainWindowHandle)) {

                driver.switchTo().window(handle);

                System.out.println("切换到新窗口: " + handle);

                break;

            }

        }

    }

    

    /**

     * 切换回主窗口

     */

    public void switchToMainWindow() {

        driver.switchTo().window(mainWindowHandle);

        System.out.println("切换回主窗口");

    }

    

    /**

     * 切换到指定窗口

     */

    public void switchToWindow(String windowHandle) {

        driver.switchTo().window(windowHandle);

        System.out.println("切换到窗口: " + windowHandle);

    }

    

    /**

     * 关闭当前窗口并切换回主窗口

     */

    public void closeCurrentWindow() {

        if (driver.getWindowHandles().size() > 1) {

            driver.close();

            switchToMainWindow();

            System.out.println("已关闭当前窗口");

        }

    }

    

    /**

     * 在不同的窗口间切换并调整尺寸

     */

    public void manageMultipleWindowsWithDifferentSizes() {

        // 记录当前窗口尺寸

        WindowSizeController sizeController = new WindowSizeController(driver);

        Dimension originalSize = sizeController.getCurrentWindowSize();

        

        // 打开新窗口并设置不同尺寸

        String originalWindow = driver.getWindowHandle();

        

        // 打开新窗口(示例:通过执行JavaScript打开新窗口)

        ((org.openqa.selenium.JavascriptExecutor) driver)

            .executeScript("window.open('about:blank', '_blank');");

        

        // 切换到新窗口

        switchToNewWindow();

        

        // 设置新窗口尺寸

        sizeController.setWindowSize(800, 600);

        

        // 打开测试页面

        driver.get("https://example.com");

        

        // 切换回原始窗口并设置不同尺寸

        switchToWindow(originalWindow);

        sizeController.setWindowSize(1024, 768);

        

        // 再次访问页面

        driver.get("https://example.com");

        

        // 关闭新窗口

        Set<String> handles = getAllWindowHandles();

        for (String handle : handles) {

            if (!handle.equals(originalWindow)) {

                switchToWindow(handle);

                closeCurrentWindow();

                break;

            }

        }

        

        // 恢复原始窗口尺寸

        sizeController.setWindowSize(originalSize.getWidth(), originalSize.getHeight());

    }

    

    /**

     * 获取所有窗口的尺寸信息

     */

    public List<WindowInfo> getAllWindowsInfo() {

        List<WindowInfo> windowsInfo = new ArrayList<>();

        String currentWindow = driver.getWindowHandle();

        

        Set<String> handles = getAllWindowHandles();

        for (String handle : handles) {

            switchToWindow(handle);

            

            WindowInfo info = new WindowInfo();

            info.setHandle(handle);

            info.setTitle(driver.getTitle());

            info.setUrl(driver.getCurrentUrl());

            

            Dimension size = driver.manage().window().getSize();

            info.setWidth(size.getWidth());

            info.setHeight(size.getHeight());

            

            Point position = driver.manage().window().getPosition();

            info.setPositionX(position.getX());

            info.setPositionY(position.getY());

            

            windowsInfo.add(info);

        }

        

        // 切换回原始窗口

        switchToWindow(currentWindow);

        

        return windowsInfo;

    }

    

    /**

     * 窗口信息类

     */

    public static class WindowInfo {

        private String handle;

        private String title;

        private String url;

        private int width;

        private int height;

        private int positionX;

        private int positionY;

        

        // Getter和Setter方法

        public String getHandle() { return handle; }

        public void setHandle(String handle) { this.handle = handle; }

        

        public String getTitle() { return title; }

        public void setTitle(String title) { this.title = title; }

        

        public String getUrl() { return url; }

        public void setUrl(String url) { this.url = url; }

        

        public int getWidth() { return width; }

        public void setWidth(int width) { this.width = width; }

        

        public int getHeight() { return height; }

        public void setHeight(int height) { this.height = height; }

        

        public int getPositionX() { return positionX; }

        public void setPositionX(int positionX) { this.positionX = positionX; }

        

        public int getPositionY() { return positionY; }

        public void setPositionY(int positionY) { this.positionY = positionY; }

        

        @Override

        public String toString() {

            return String.format(

                "Window{handle=%s, title='%s', size=%dx%d, position=(%d,%d)}",

                handle.substring(0, Math.min(8, handle.length())),

                title,

                width, height,

                positionX, positionY

            );

        }

    }

}

```


### 响应式设计测试


```java

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.OutputType;

import org.openqa.selenium.TakesScreenshot;

import org.apache.commons.io.FileUtils;

import java.io.File;

import java.io.IOException;

import java.text.SimpleDateFormat;

import java.util.Date;


public class ResponsiveDesignTester {

    

    private final WebDriver driver;

    private final String screenshotDir;

    

    public ResponsiveDesignTester(WebDriver driver, String screenshotDir) {

        this.driver = driver;

        this.screenshotDir = screenshotDir;

        createScreenshotDirectory();

    }

    

    private void createScreenshotDirectory() {

        File dir = new File(screenshotDir);

        if (!dir.exists()) {

            dir.mkdirs();

        }

    }

    

    /**

     * 测试不同分辨率下的页面显示

     */

    public void testResponsiveBreakpoints() {

        // 定义响应式断点

        int[][] breakpoints = {

            {320, 480},   // 小手机

            {375, 667},   // iPhone 6/7/8

            {414, 896},   // iPhone XR/11

            {768, 1024},  // 平板竖屏

            {1024, 768},  // 平板横屏

            {1366, 768},  // 笔记本

            {1920, 1080}  // 桌面

        };

        

        WindowSizeController sizeController = new WindowSizeController(driver);

        

        for (int[] breakpoint : breakpoints) {

            int width = breakpoint[0];

            int height = breakpoint[1];

            

            // 设置窗口尺寸

            sizeController.setWindowSize(width, height);

            

            // 等待页面调整

            waitForPageToAdjust();

            

            // 截屏

            takeScreenshot(width + "x" + height);

            

            // 记录信息

            System.out.printf("测试分辨率: %dx%d - 页面标题: %s%n",

                width, height, driver.getTitle());

        }

    }

    

    /**

     * 逐步调整窗口尺寸并观察页面变化

     */

    public void testContinuousResize() {

        WindowSizeController sizeController = new WindowSizeController(driver);

        Dimension currentSize = sizeController.getCurrentWindowSize();.

www.ko.wandaihu.cn>www.qm.wandaihu.cn>

        

        // 从最小尺寸逐渐增加到最大尺寸

        int startWidth = 320;

        int endWidth = 1920;

        int step = 100;

        

        for (int width = startWidth; width <= endWidth; width += step) {

            // 保持宽高比

            int height = (int) (width * 0.5625); // 16:9比例

            

            sizeController.setWindowSize(width, height);

            waitForPageToAdjust();

            

            // 检查页面布局变化

            checkLayoutChanges(width);

            

            // 每200像素截屏一次

            if (width % 200 == 0) {

                takeScreenshot("resize_" + width + "x" + height);

            }

        }

        

        // 恢复原始尺寸

        sizeController.setWindowSize(currentSize.getWidth(), currentSize.getHeight());

    }

    

    /**

     * 等待页面适应新尺寸

     */

    private void waitForPageToAdjust() {

        try {

            // 等待CSS和JavaScript调整

            Thread.sleep(500);

            

            // 也可以使用WebDriverWait等待特定条件

            // WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(5));

            // wait.until(ExpectedConditions.jsReturnsValue("return document.readyState === 'complete'"));

            

        } catch (InterruptedException e) {

            Thread.currentThread().interrupt();

        }

    }

    

    /**

     * 截屏并保存

     */

    private void takeScreenshot(String prefix) {

        try {

            // 生成时间戳

            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd_HHmmss");

            String timestamp = dateFormat.format(new Date());

            

            // 截屏

            File screenshot = ((TakesScreenshot) driver)

                .getScreenshotAs(OutputType.FILE);

            

            // 保存文件

            String filename = String.format("%s/%s_%s.png", 

                screenshotDir, prefix, timestamp);

            FileUtils.copyFile(screenshot, new File(filename));

            

            System.out.println("截屏保存到: " + filename);

            

        } catch (IOException e) {

            System.err.println("截屏失败: " + e.getMessage());

        }

    }

    

    /**

     * 检查页面布局变化

     */

    private void checkLayoutChanges(int currentWidth) {

        try {

            // 使用JavaScript检查视口宽度

            Object viewportWidth = ((org.openqa.selenium.JavascriptExecutor) driver)

                .executeScript("return window.innerWidth");

            

            // 检查是否应用了响应式样式

            Object isMobile = ((org.openqa.selenium.JavascriptExecutor) driver)

                .executeScript("return window.matchMedia('(max-width: 768px)').matches");

            

            Object isTablet = ((org.openqa.selenium.JavascriptExecutor) driver)

                .executeScript("return window.matchMedia('(min-width: 769px) and (max-width: 1024px)').matches");

            

            Object isDesktop = ((org.openqa.selenium.JavascriptExecutor) driver)

                .executeScript("return window.matchMedia('(min-width: 1025px)').matches");

            

            System.out.printf("当前宽度: %d, 视口宽度: %s, 移动端: %s, 平板: %s, 桌面: %s%n",

                currentWidth, viewportWidth, isMobile, isTablet, isDesktop);

            

        } catch (Exception e) {

            System.err.println("检查布局时出错: " + e.getMessage());

        }

    }

}

```


## 实战应用示例


### 测试页面布局


```java

import org.openqa.selenium.By;

import org.openqa.selenium.WebElement;

import org.openqa.selenium.support.ui.WebDriverWait;

import org.openqa.selenium.support.ui.ExpectedConditions;

import java.time.Duration;

www.rp.wandaihu.cn>www.py.wandaihu.cn>


public class LayoutTestingExample {

    

    private final WebDriver driver;

    private final WindowSizeController sizeController;

    

    public LayoutTestingExample(WebDriver driver) {

        this.driver = driver;

        this.sizeController = new WindowSizeController(driver);

    }

    

    /**

     * 测试导航栏在不同尺寸下的显示

     */

    public void testNavigationBarResponsiveness() {

        // 访问测试页面

        driver.get("https://example.com");

        

        // 定义测试尺寸

        int[][] testSizes = {

            {320, 480},   // 小手机

            {768, 1024},  // 平板

            {1024, 768},  // 桌面小

            {1920, 1080}  // 桌面大

        };

        

        for (int[] size : testSizes) {

            int width = size[0];

            int height = size[1];

            

            // 设置尺寸

            sizeController.setWindowSize(width, height);

            

            // 等待页面加载

            WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(5));

            

            // 检查导航栏元素

            try {

                if (width < 768) {

                    // 移动端:检查汉堡菜单是否可见

                    WebElement hamburgerMenu = wait.until(

                        ExpectedConditions.visibilityOfElementLocated(

                            By.cssSelector(".hamburger-menu, .mobile-menu-toggle")

                        )

                    );

                    System.out.printf("移动端(%dx%d): 汉堡菜单可见: %s%n",

                        width, height, hamburgerMenu.isDisplayed());

                    

                } else {

                    // 桌面端:检查完整导航栏是否可见

                    WebElement navBar = wait.until(

                        ExpectedConditions.visibilityOfElementLocated(

                            By.cssSelector("nav, .navbar, .main-navigation")

                        )

                    );

                    System.out.printf("桌面端(%dx%d): 导航栏可见: %s,宽度: %d%n",

                        width, height, navBar.isDisplayed(), navBar.getSize().getWidth());

                }

                

                // 检查logo是否可见

                WebElement logo = driver.findElement(

                    By.cssSelector(".logo, [class*='logo'], img[alt*='logo']")

                );

                System.out.printf("  Logo尺寸: %dx%d%n",

                    logo.getSize().getWidth(), logo.getSize().getHeight());

                

            } catch (Exception e) {

                System.out.printf("尺寸 %dx%d 测试失败: %s%n",

                    width, height, e.getMessage());

            }

            

            // 短暂暂停

            try {

                Thread.sleep(1000);

            } catch (InterruptedException e) {

                Thread.currentThread().interrupt();

            }

        }

    }

    

    /**

     * 测试表格或数据展示的响应式

     */

    public void testDataTableResponsiveness() {

        driver.get("https://example.com/tables");

        

        // 逐步减小宽度,观察表格变化

        for (int width = 1200; width >= 300; width -= 100) {

            int height = 800; // 固定高度

            

            sizeController.setWindowSize(width, height);

            waitForPageToAdjust();

            

            try {

                // 查找表格

                WebElement table = driver.findElement(By.tagName("table"));

                

                // 检查是否出现水平滚动

                boolean hasHorizontalScroll = (Boolean) ((org.openqa.selenium.JavascriptExecutor) driver)

                    .executeScript("return document.documentElement.scrollWidth > document.documentElement.clientWidth");

                

                // 检查表格宽度

                int tableWidth = table.getSize().getWidth();

                int viewportWidth = driver.manage().window().getSize().getWidth();

                

                System.out.printf("宽度 %d: 表格宽度 %d, 视口宽度 %d, 水平滚动: %s%n",

                    width, tableWidth, viewportWidth, hasHorizontalScroll);

                

                // 如果表格宽度超过视口,可能出现了响应式调整

                if (tableWidth > viewportWidth && width < 600) {

                    System.out.println("  注意:在小屏幕上表格可能需要水平滚动");

                }

                

            } catch (Exception e) {

                System.out.printf("宽度 %d: 未找到表格或检查失败%n", width);

            }

        }

    }

    

    /**

     * 验证不同分辨率下的表单布局

     */

    public void testFormLayoutResponsiveness() {

        driver.get("https://example.com/contact");

        

        // 测试尺寸

        int[][] resolutions = {

            {375, 667},   // iPhone 竖屏

            {667, 375},   // iPhone 横屏

            {768, 1024},  // iPad 竖屏

            {1024, 768},  // iPad 横屏

            {1366, 768},  // 笔记本

            {1920, 1080}  // 桌面

        };

        

        for (int[] res : resolutions) {

            sizeController.setWindowSize(res[0], res[1]);

            waitForPageToAdjust();

            

            System.out.printf("\n测试分辨率: %dx%d%n", res[0], res[1]);

            

            // 检查表单元素

            checkFormElement("input[type='text'], input[type='email']", "文本输入框");

            checkFormElement("textarea", "文本区域");

            checkFormElement("select", "下拉选择");

            checkFormElement("button[type='submit'], input[type='submit']", "提交按钮");

        }

    }

    

    private void checkFormElement(String cssSelector, String elementName) {

        try {

            WebElement element = driver.findElement(By.cssSelector(cssSelector));

            System.out.printf("  %s: 可见=%s, 尺寸=%dx%d, 位置=(%d,%d)%n",

                elementName,

                element.isDisplayed(),

                element.getSize().getWidth(),

                element.getSize().getHeight(),

                element.getLocation().getX(),

                element.getLocation().getY()

            );

        } catch (Exception e) {

            System.out.printf("  %s: 未找到%n", elementName);

        }

    }

    

    private void waitForPageToAdjust() {

        try {

            Thread.sleep(800);

        } catch (InterruptedException e) {

            Thread.currentThread().interrupt();

        }

    }

}

```


### 性能优化与最佳实践


```java

import org.openqa.selenium.JavascriptExecutor;


public class WindowManagementBestPractices {

    

    private final WebDriver driver;

    

    public WindowManagementBestPractices(WebDriver driver) {

        this.driver = driver;

    }www.kw.wandaihu.cn>www.dw.wandaihu.cn>

    

    /**

     * 优化窗口管理的通用方法

     */

    public void optimizedWindowSetup() {

        WindowSizeController controller = new WindowSizeController(driver);

        

        // 1. 先最大化窗口确保获取最大可用空间

        controller.maximizeWindow();

        

        // 2. 获取屏幕信息

        Dimension screenSize = getScreenSize();

        System.out.println("屏幕尺寸: " + screenSize.getWidth() + "x" + screenSize.getHeight());

        

        // 3. 设置合理的测试尺寸(考虑到任务栏和浏览器边框)

        int testWidth = screenSize.getWidth() - 100;

        int testHeight = screenSize.getHeight() - 150;

        

        controller.setWindowSize(testWidth, testHeight);

        

        // 4. 验证实际尺寸

        Dimension actualSize = controller.getCurrentWindowSize();

        System.out.println("实际窗口尺寸: " + actualSize.getWidth() + "x" + actualSize.getHeight());

    }

    

    /**

     * 获取屏幕尺寸

     */

    private Dimension getScreenSize() {

        try {

            // 使用JavaScript获取屏幕尺寸

            JavascriptExecutor js = (JavascriptExecutor) driver;

            

            // 临时最大化以获取准确屏幕尺寸

            driver.manage().window().maximize();

            

            // 通过多个属性获取最准确的值

            Long screenWidth = (Long) js.executeScript(

                "return Math.max(window.screen.width, window.screen.availWidth)");

            Long screenHeight = (Long) js.executeScript(

                "return Math.max(window.screen.height, window.screen.availHeight)");

            

            return new Dimension(screenWidth.intValue(), screenHeight.intValue());

            

        } catch (Exception e) {

            // 回退到默认值

            return new Dimension(1920, 1080);

        }

    }

    

    /**

     * 安全的窗口尺寸切换

     */

    public void safeWindowResize(int targetWidth, int targetHeight) {

        Dimension currentSize = driver.manage().window().getSize();

        Point currentPosition = driver.manage().window().getPosition();

        

        try {

            // 验证目标尺寸是否合理

            if (targetWidth <= 100 || targetHeight <= 100) {

                System.out.println("警告:目标尺寸过小,调整到最小值");

                targetWidth = Math.max(100, targetWidth);

                targetHeight = Math.max(100, targetHeight);

            }

            

            Dimension screenSize = getScreenSize();

            if (targetWidth > screenSize.getWidth() || targetHeight > screenSize.getHeight()) {

                System.out.println("警告:目标尺寸超过屏幕大小,调整为最大值");

                targetWidth = Math.min(targetWidth, screenSize.getWidth());

                targetHeight = Math.min(targetHeight, screenSize.getHeight());

            }

            

            // 执行调整

            driver.manage().window().setSize(new Dimension(targetWidth, targetHeight));

            

            // 验证调整成功

            Dimension newSize = driver.manage().window().getSize();

            if (Math.abs(newSize.getWidth() - targetWidth) > 10 || 

                Math.abs(newSize.getHeight() - targetHeight) > 10) {

                System.out.println("警告:实际尺寸与目标尺寸有差异");

                System.out.println("目标: " + targetWidth + "x" + targetHeight);

                System.out.println("实际: " + newSize.getWidth() + "x" + newSize.getHeight());

            }

            

        } catch (Exception e) {

            System.out.println("窗口调整失败,恢复原始尺寸: " + e.getMessage());

            // 恢复原始尺寸和位置

            driver.manage().window().setPosition(currentPosition);

            driver.manage().window().setSize(currentSize);

        }

    }

    

    /**

     * 批量窗口操作模板

     */

    public void batchWindowOperations(Runnable... operations) {

        // 保存原始状态

        String originalWindow = driver.getWindowHandle();

        Dimension originalSize = driver.manage().window().getSize();

        Point originalPosition = driver.manage().window().getPosition();

        

        try {

            // 执行所有操作

            for (Runnable operation : operations) {

                operation.run();

            }

            

        } finally {

            // 恢复原始状态

            driver.switchTo().window(originalWindow);

            driver.manage().window().setPosition(originalPosition);

            driver.manage().window().setSize(originalSize);

        }

    }

    

    /**

     * 异步窗口操作

     */

    public void asyncWindowOperation(Runnable operation, int timeoutSeconds) {

        Thread operationThread = new Thread(() -> {

            try {

                operation.run();

            } catch (Exception e) {

                System.err.println("异步窗口操作失败: " + e.getMessage());

            }

        });

        

        operationThread.start();

        

        // 等待操作完成或超时

        try {

            operationThread.join(timeoutSeconds * 1000);

            

            if (operationThread.isAlive()) {

                System.out.println("窗口操作超时,正在中断...");

                operationThread.interrupt();

            }

            

        } catch (InterruptedException e) {

            Thread.currentThread().interrupt();

        }

    }

}

```


## 测试框架集成


### JUnit 5测试示例


```java

import org.junit.jupiter.api.*;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;

import io.github.bonigarcia.wdm.WebDriverManager;


import static org.junit.jupiter.api.Assertions.*;


@TestInstance(TestInstance.Lifecycle.PER_CLASS)

class WindowSizeJUnitTest {

    

    private WebDriver driver;

    private WindowSizeController sizeController;

    

    @BeforeAll

    static void setupAll() {

        WebDriverManager.chromedriver().setup();

    }

    

    @BeforeEach

    void setup() {

        driver = new ChromeDriver();

        sizeController = new WindowSizeController(driver);

        

        // 访问测试页面

        driver.get("https://example.com");

    }

    

    @Test

    @DisplayName("测试窗口尺寸设置功能")

    void testWindowSizeSetting() {

        // 测试设置特定尺寸

        sizeController.setWindowSize(800, 600);

        

        Dimension size = sizeController.getCurrentWindowSize();

        assertEquals(800, size.getWidth());

        assertEquals(600, size.getHeight());

        

        // 测试最大化

        sizeController.maximizeWindow();

        Dimension maxSize = sizeController.getCurrentWindowSize();

        assertTrue(maxSize.getWidth() >= 800);

        assertTrue(maxSize.getHeight() >= 600);

    }

    

    @Test

    @DisplayName("测试多个分辨率切换")

    void testMultipleResolutions() {

        StandardResolutions resolutions = new StandardResolutions(driver);

        

        // 测试不同设备分辨率

        resolutions.setToDeviceResolution(

            StandardResolutions.DeviceResolution.MOBILE_375x667);

        

        Dimension mobileSize = sizeController.getCurrentWindowSize();

        assertEquals(375, mobileSize.getWidth());

        assertEquals(667, mobileSize.getHeight());

        

        // 切换到桌面分辨率

        resolutions.setToDeviceResolution(

            StandardResolutions.DeviceResolution.DESKTOP_1920x1080);

        

        Dimension desktopSize = sizeController.getCurrentWindowSize();

        assertTrue(desktopSize.getWidth() >= 1900);

        assertTrue(desktopSize.getHeight() >= 1000);

    }

    

    @Test

    @DisplayName("测试窗口位置设置")

    void testWindowPosition() {

        // 设置窗口位置

        Point targetPosition = new Point(100, 100);

        driver.manage().window().setPosition(targetPosition);

        

        Point actualPosition = driver.manage().window().getPosition();

        assertEquals(100, actualPosition.getX());

        assertEquals(100, actualPosition.getY());

        

        // 验证位置在屏幕范围内

        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();

        assertTrue(actualPosition.getX() >= 0);

        assertTrue(actualPosition.getY() >= 0);

        assertTrue(actualPosition.getX() < screenSize.getWidth());

        assertTrue(actualPosition.getY() < screenSize.getHeight());

    }

    

    @Test

    @DisplayName("测试响应式布局")

    void testResponsiveLayout() {

        LayoutTestingExample layoutTester = new LayoutTestingExample(driver);

        

        // 测试不同尺寸下的导航栏

        assertDoesNotThrow(() -> {

            layoutTester.testNavigationBarResponsiveness();

        });

        

        // 验证页面在不同尺寸下都能正常访问

        int[] testWidths = {320, 768, 1024, 1920};

        

        for (int width : testWidths) {

            sizeController.setWindowSize(width, 800);

            

            // 验证页面标题存在

            String title = driver.getTitle();

            assertNotNull(title);

            assertFalse(title.trim().isEmpty());

            

            // 验证页面主体可见

            boolean isBodyVisible = driver.findElement(By.tagName("body")).isDisplayed();

            assertTrue(isBodyVisible, "页面主体在宽度" + width + "下应可见");

        }

    }

    

    @AfterEach

    void teardown() {

        if (driver != null) {


来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/19545/viewspace-3105617/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2015-11-01

  • 博文量
    895
  • 访问量
    933968