在尝试将硒重新连接到铬会议时,我遇到了一个错误的错误:
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)
要重新连接会话而不初始化新窗口,使用猴子补丁from another stackoverflow question - 粘贴在@TarunLalwani下面
browser = webdriver.Chrome(executable_path=path_to_chrome)
browser.get(url)
这个猴子补丁正在改变发生错误的钥匙,所以我相信问题就在那里,但我不太明白猴子补丁发生了什么。
如果猴子补丁尚未作为一个函数加载, 将运行,但如果它已经加载,则不会运行,因此会出现上述错误。
此外,在加载猴子补丁后运行以下
<ipython-input-4-9615267dd764> in new_command_execute(self, command, params)
14 return {'success': 0, 'value': None, 'sessionId':
session_id}
15 else:
---> 16 return org_command_execute(self, command, params)
会导致错误,即使我只是调用webdriver而不是尝试重用会话,这似乎也在访问猴子补丁。
{{1}}
我如何尝试解决此问题?
答案 0 :(得分:0)
而不是修复上述内容,我只是在函数外部声明浏览器并将其传递给我正在使用的函数。例如:
browser = webdriver.Chrome(executable_path=path_to_chrome)
browser.get(url)
somefunction(browser)
而不是
somefunction(session_id, session_url)
在某些方面不那么优雅,但更简单。