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 IE
) I use.
I can set browser window size as follow:
driver.set_window_size(1920, 1080)
But following code will return different values for Chrome
and IE
:
element = driver.find_element_by_xpath('some_xpath')
element.location
as viewport area (where web-content displayed) sizes are different (Chrome
- 1910x998, IE
- 1904x965) despite of same window size. To get these values I used
driver.execute_script('return document.documentElement.clientHeight')
driver.execute_script('return document.documentElement.clientWidth')
so I tried
driver.execute_script('document.documentElement.clientHeight = "990px";')
driver.execute_script('document.documentElement.clientWeight = "1900px";')
but with no luck
So the question is how to set browser viewport size in selenium
?
There are two ways to set the browser's size: using the selenium web-driver or using the Eyes. open method. Note that this results in changing the browser size to have its viewport (viewable content frame size) to match the parameter and not the entire browser window.
You can use the window. innerHeight property to get the viewport height, and the window. innerWidth to get its width. let viewportHeight = window.
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];")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With