I am using python to interact with webpages via selenium. I am using the geckodriver Firefox driver (not interested in Chrome solutions).
I want to zoom the browser window, equivalent to pressing ctrl
+-
(or cmd
+-
on Mac OS).
Granted, there are lots of questions on this topic. I have tried to do my due diligence in digging through them before posting here. The following are solutions that do not work for me (let driver
be a WebDriver
instance running with geckodriver):
No effect:
driver.execute_script("document.body.style.zoom='zoom 90%'")
from selenium.webdriver.common.keys import Keys
body = driver.find_element_by_tag_name('body')
body.send_keys(Keys.COMMAND, Keys.SUBTRACT)
from selenium.webdriver.common.action_chains import ActionChains
actor = ActionChains(driver)
actor.key_down(Keys.COMMAND).key_down(Keys.SUBTRACT).perform()
Wrong effect:
driver.execute_script("document.body.style.transform='scale(0.9)'")
driver.execute_script("document.body.style.MozTransform='scale(0.9)'")
Error:
driver.set_context("chrome")
win = driver.find_element_by_tag_name("window")
win.send_keys(Keys.CONTROL + "-")
driver.set_context("content")
(raises NoSuchElementException
)
Related questions:
...and many others.
The only way I have found that actually works is to use pyautogui
, however I would rather not install additional 3rd-party libraries, & I don't believe I'll be able to run this in a headless state without a lot of hassle.
However, it seems there should be some way to do this using Selenium/geckodriver's native functionality, rather than installing additional 3rd-party packages for this purpose.
Is there a way??? The abundance of questions on this topic makes it clear that I am not the only one to have had trouble with this...
EDIT: Testing on Python 3.9, Selenium 3.141.0, geckodriver 0.29.1, Firefox 90.0, Mac OS
In Python 3.7.7, selenium 3.141.0, geckodriver 0.29.1, firefox 90.0, Ubuntu 20.04.2 LTS, I combined 2 of your items and made it work.
I could not find the window tag either, but I found body. After I got the url (and only after, otherwise I got an error), I had to do the set context to "chrome." I don't know why, but if not, as you observed, nothing happened. Then I was able to send control + or control - with the desired effect (I took two + to really see the difference, but the 110% and then 120% also shows).
driver.get(URL)#URL is a constant containing the url
driver.set_context("chrome")#needed to make keys work, must come after there is a context
win = driver.find_element_by_tag_name("body")#there is a body even if not a window
win.send_keys(Keys.CONTROL, "+")#zoom to 110%
win.send_keys(Keys.CONTROL, "+")#zoom to 120%