[Python] attach to an existing session

This is my note to attach to an existing Selenium/Appium session in Python. It is useful to debug/develop Selenium/Appium stuff.

def attach_to_session(executor_url, session_id):
    original_execute = WebDriver.execute
    def new_command_execute(self, command, params=None):
        if command == 'newSession':
            return {'value': None, 'sessionId': session_id}
        else:
            return original_execute(self, command, params)
    WebDriver.execute = new_command_execute
    driver = webdriver.Remote(command_executor=executor_url, desired_capabilities={})
    driver.session_id = session_id
    WebDriver.execute = original_execute
    return driver

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.