Can we Zoom the browser window in python selenium webdriver?

后端 未结 5 736
不思量自难忘°
不思量自难忘° 2020-12-14 10:52

I am trying to ZOOM IN and ZOOM OUT the Chrome( selenium webdriver) only using keyboard. I have tried --

from selenium.webdriver.common.keys import Keys
driv         


        
5条回答
  •  忘掉有多难
    2020-12-14 11:41

    Yes, you can invoke the Chrome driver to zoom without having to use CSS. There are methods packaged into the Chrome DevTools Protocol Viewer, one being Input.synthesizePinchGesture aka zoom in/out.

    For ease of use, with regards to the DevTools Protocol API, we will use a class called MyChromeDriver with webdriver.Chrome as a metaclass and a new method for sending these commands to Chrome:

    # selenium
    from selenium import webdriver
    # json
    import json
    
    class MyChromeDriver(webdriver.Chrome):
        def send_cmd(self, cmd, params):
            resource = "/session/%s/chromium/send_command_and_get_result" % self.session_id
            url = self.command_executor._url + resource
            body = json.dumps({'cmd':cmd, 'params': params})
            response = self.command_executor._request('POST', url, body)
            return response.get('value')
    

    1. Setup our webdriver and get some page:

    webdriver = MyChromeDriver()
    webdriver.get("https://google.com")
    

    2. Send Chrome the Input.synthesizePinchGesture command along with its parameters via our new method send_cmd:

    webdriver.send_cmd('Input.synthesizePinchGesture', {
                            'x': 0,
                            'y': 0,
                            'scaleFactor': 2,
                            'relativeSpeed': 800, # optional
                            'gestureSourceType': 'default' # optional
                        })
    

    3. Walla! Chrome's zoom is invoked:

    As a side note, there are tons of other commands you could use with send_cmd. Find them here: https://chromedevtools.github.io/devtools-protocol/

    Based off this answer: Take full page screen shot in Chrome with Selenium

提交回复
热议问题