0

I'm trying to re-attach to existing Chrome session, with user-data-dir chrome_option. While it works with non-headless, it doesn't do anything when in headless mode. It worked a couple of months ago, following this guide: I can reattach to session with selenium but cannot stop it launching another browser? , but not any more. Any clues on how to do it?

Here is my code:

executor_url = driver2.command_executor._url
session_id = driver2.session_id
time.sleep(2)

driver2.get("https://www.google.com")
print(driver2.current_url)
time.sleep(5)
driver2.get_screenshot_as_file('capture0.png')

def create_driver_session(session_id, executor_url):
    from selenium.webdriver.remote.webdriver import WebDriver as RemoteWebDriver

    # Save the original function, so we can revert our patch
    org_command_execute = RemoteWebDriver.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 org_command_execute(self, command, params)

    # Patch the function before creating the driver object
    RemoteWebDriver.execute = new_command_execute

    new_driver = webdriver.Remote(command_executor=executor_url, desired_capabilities={})
    new_driver.session_id = session_id

    # Replace the patched function with original function
    RemoteWebDriver.execute = org_command_execute

    return new_driver

driver2 = create_driver_session(session_id, executor_url)
print(driver2.current_url)

Thanks!

0 Answers0