9Z WebDriver – 最大化窗口

    嗨冠军! 事情并非总是以我们希望的方式运作,这就是挑战的形式。 使用 Selenium Webdriver,我们的测试工作变得比我们期望的要容易得多。 一种这样的情况是最大化浏览器窗口。

    屏幕截图可以节省生命,为了在抓取时查看所有 Web 元素,最大化浏览器窗口非常重要。 因此,与其向下滚动到特定元素,不如最大化窗口并完成手头的任务。

    1. 打开 Firefox 浏览器
    2. 导航到
    3. 获取当前的窗口句柄
    4. 使用 ID 定位“单击以打开一个小窗口!”按钮
    5. 点击按钮打开小窗口
    6. 获取两个打开的窗口的窗口句柄
    7. 通过两个句柄循环
    8. 切换到带有句柄参考的新窗口
    9. 获取标题并将其打印到控制台
    10. 将小窗口最大化到全屏尺寸
    11. 关闭新窗口
    12. 将控件切换回父窗口,然后将 URL 打印到控制台
    13. 验证 Eclipse IDE 控制台输出屏幕和 JUnit 窗格是否成功

    此方案的 JUnit 代码是,

    1. import java.util.Set;
    2. import java.util.concurrent.TimeUnit;
    3. import org.junit.After;
    4. import org.junit.Before;
    5. import org.junit.Test;
    6. import org.openqa.selenium.By;
    7. import org.openqa.selenium.WebDriver;
    8. import org.openqa.selenium.firefox.FirefoxDriver;
    9. public class WindowMaximize {
    10. // Declaring variables
    11. private WebDriver driver;
    12. private String baseUrl;
    13. @Before
    14. public void setUp() throws Exception {
    15. System.setProperty("webdriver.gecko.driver", "E:\\Softwares\\"
    16. + "Selenium\\geckodriver-v0.10.0-win64\\geckodriver.exe");
    17. // Create a new instance for the class FirefoxDriver
    18. // that implements WebDriver interface
    19. driver = new FirefoxDriver();
    20. // Implicit wait for 5 seconds
    21. driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
    22. // Assign the URL to be invoked to a String variable
    23. baseUrl = "https://chandanachaitanya.github.io/selenium-practice-site/";
    24. }
    25. @Test
    26. public void testPageTitle() throws Exception {
    27. // Open baseUrl in Firefox browser window
    28. // Get current window handle
    29. String parentWinHandle = driver.getWindowHandle();
    30. // Locate 'Click to open a small window!' button using id
    31. // Click the button to open a new window
    32. newWindowBtn.click();
    33. // Get the window handles of all open windows
    34. Set<String> winHandles = driver.getWindowHandles();
    35. // Loop through all handles
    36. for (String handle : winHandles) {
    37. if (!handle.equals(parentWinHandle)) {
    38. driver.switchTo().window(handle);
    39. System.out.println("Title of the new window: " + driver.getTitle());
    40. // Maximize the new window
    41. driver.manage().window().maximize();
    42. driver.close();
    43. }
    44. }
    45. // Switching the control back to parent window
    46. driver.switchTo().window(parentWinHandle);
    47. // Print the URL to the console
    48. System.out.println("Parent window URL: " + driver.getCurrentUrl());
    49. } // End of @Test

    执行结果:

    清晰的注释使代码不言自明。

    如有任何疑问,请不要在评论部分大喊大叫!