How to get window size, resize or maximize window using Selenium WebDriver
Recently Updated - January 16, 2017
Selenium WebDriver supports getting the browser window size, resizing and maximizing window natively from its API, no JavaScript injections like window.resizeTo(X, Y);
are necessary any more. Below shows the examples on how to achieve this in Selenium WebDriver C#, Ruby and Python bindings.
Ruby
In Ruby binding, window size can be retrieved from method driver.manage.window.size
, which is a type of struct Selenium::WebDriver::Dimension
defined here. To resize a window, one solution is to create a new Dimension
object and assign it to property driver.manage.window.size
. Alternatively, Ruby binding has provided a driver.manage.window.resize_to()
method, which is equivalent to #size=
, but accepts width and height arguments according to API here.
Environment Tested:
Mac OS Sierra, Ruby 2.3.1p112, Selenium 3.0.5, ChromDriver 2.26, GeckoDriver 0.13
Firefox 50.1, Chrome 55, PhantomJS 1.9.8
Example
Output
#<struct Selenium::WebDriver::Dimension width=1341, height=810>
#<struct Selenium::WebDriver::Dimension width=1024, height=768>
#<struct Selenium::WebDriver::Dimension width=480, height=320>
#<struct Selenium::WebDriver::Dimension width=1804, height=1096>
C#
Similarly in C# binding, a browser window's size can be found out using driver.Manage().Window.Size
property. The same IWindow interface also defines method Maximize()
for maximizing the window. Although this interface doesn't provide a function to resize window directly like Ruby binding, it can be done by setting the Size
property using System.Drawing.Size
object1.
Environment Tested:
Windows 7, Selenium 2.39.0, Firefox 26.0
Example
Output
{Width=1341, Height=810}
{Width=480, Height=320}
{Width=1804, Height=1096}
Python
Unlike C# and Ruby bindings, Python binding doesn't offer properties to get/set window size, all get/set/maximize actions are available using methods defined in selenium.webdriver.remote.webdriver.
Environment Tested:
Window 7, Python 2.7, Selenium 2.40.0, Firefox 26.0
Example
Output
{u'width': 1341, u'height': 810}
{u'width': 480, u'height': 320}
{u'width': 1804, u'height': 1096}
Comparison
Get window size | |
---|---|
Ruby | driver.manage.window.size |
C# | driver.Manage().Window.Size; |
Python | driver.get_window_size() |
Set window size | |
Ruby | size = Selenium::WebDriver::Dimension.new(width, height) driver.manage.window.size = size |
C# | System.Drawing.Size windowSize = new System.Drawing.Size(width, height); driver.Manage().Window.Size = windowSize; |
Python | - |
Resize window | |
Ruby | driver.manage.window.resize_to(width, height) |
C# | - |
Python | driver.set_window_size(width, height) |
Maximize window | |
Ruby | driver.manage.window.maximize |
C# | driver.Manage().Window.Maximize(); |
Python | driver.maximize_window() |
Related source code
-
Adding "System.Drawing" assembly reference to project is required first. ↩