How to set browser viewport size

后端 未结 3 2165
野趣味
野趣味 2021-02-20 13:29

I\'m trying to create a cross-browser Python-Selenium test script. So I need all results to be same no matter which webdriver (Chrome or <

相关标签:
3条回答
  • 2021-02-20 13:50

    Here is function to set the viewport size:

    def set_viewport_size(driver, width, height):
        window_size = driver.execute_script("""
            return [window.outerWidth - window.innerWidth + arguments[0],
              window.outerHeight - window.innerHeight + arguments[1]];
            """, width, height)
        driver.set_window_size(*window_size)
    

    Usage :

    from selenium import webdriver
    
    driver = webdriver.Chrome()
    
    # set the viewport size to 800 x 600
    set_viewport_size(driver, 800, 600)
    
    # display the viewport size
    print driver.execute_script("return [window.innerWidth, window.innerHeight];")
    
    0 讨论(0)
  • 2021-02-20 14:12

    Here's the Java version for @Florent B. answer :

            int width = "500";
            int height = "500";
    
            //Remove the window from fullscreen (optional), if it s in fullscreen the outerHeight is not accurate
            browser.manage().window().setSize(new Dimension(800,800));
    
            JavascriptExecutor js= (JavascriptExecutor)browser;
    
            String windowSize = js.executeScript("return (window.outerWidth - window.innerWidth + "+width+") + ',' + (window.outerHeight - window.innerHeight + "+height+"); ").toString();
    
            //Get the values
            width = Integer.parseInt(windowSize.split(",")[0]);
            height = Integer.parseInt(windowSize.split(",")[1]);
    
            //Set the window
            browser.manage().window().setSize(new Dimension(width, height));
    
    0 讨论(0)
  • 2021-02-20 14:15

    I'm using this:

    driver.manage().window().setSize(new org.openqa.selenium.Dimension(1900, 990));
    

    Where 1900 is the width, and 990 is the height.

    0 讨论(0)
提交回复
热议问题