Chrome 我可以用Selenium重新连接会话,但无法阻止它启动另一个浏览器?

lyr7nygr  于 2023-03-16  发布在  Go
关注(0)|答案(1)|浏览(156)

这是我的代码,它确实附加到旧的会话,但是在调用webdriver.Remote()时,它会使另一个浏览器启动!!无缘无故?这是在Mac上,其他人有这个问题吗?(它使这个功能毫无用处)
谁能告诉我我做错了什么?

from selenium import webdriver

driver = webdriver.Chrome()
url = driver.command_executor._url
session_id = driver.session_id 

driver.get('https://www.w3schools.com/html/tryit.asp?filename=tryhtml_intro')

driver2 = webdriver.Remote(command_executor=url,desired_capabilities={})
driver2.session_id = session_id

driver2.get("http://www.wikipedia.in")
waxmsbnn

waxmsbnn1#

你可以做到这一点,但它需要对selenium代码进行一些修补,这可以通过在python中使用monkey修补来完成。

from selenium import webdriver

driver = webdriver.Firefox()
executor_url = driver.command_executor._url
session_id = driver.session_id
driver.get("http://tarunlalwani.com")

print session_id
print executor_url

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

解决方案的关键是不要让newSession命令通过原始驱动程序执行,而是发送我们自己现有的会话ID来处理它。我们将在下面的部分中这样做

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)

PS:http://tarunlalwani.com/post/reusing-existing-browser-session-selenium/上提供详细文章

相关问题