Can Selenium interact with an existing browser session?

后端 未结 11 993
野性不改
野性不改 2020-11-22 08:47

Does anybody know if Selenium (WebDriver preferably) is able to communicate with and act through a browser that is already running before launching a Selenium Client?

11条回答
  •  天涯浪人
    2020-11-22 09:20

    This snippet successfully allows to reuse existing browser instance yet avoiding raising the duplicate browser. Found at Tarun Lalwani's blog.

    from selenium import webdriver
    from selenium.webdriver.remote.webdriver import WebDriver
    
    # executor_url = driver.command_executor._url
    # session_id = driver.session_id
    
    def attach_to_session(executor_url, session_id):
        original_execute = WebDriver.execute
        def new_command_execute(self, command, params=None):
            if command == "newSession":
                # Mock the response
                return {'success': 0, 'value': None, 'sessionId': session_id}
            else:
                return original_execute(self, command, params)
        # Patch the function before creating the driver object
        WebDriver.execute = new_command_execute
        driver = webdriver.Remote(command_executor=executor_url, desired_capabilities={})
        driver.session_id = session_id
        # Replace the patched function with original function
        WebDriver.execute = original_execute
        return driver
    
    bro = attach_to_session('http://127.0.0.1:64092', '8de24f3bfbec01ba0d82a7946df1d1c3')
    bro.get('http://ya.ru/')
    

提交回复
热议问题