I have a script in Python that uses Selenium to automatically navigate the web.
I'm upgrading my script to make it work even if Chrome has already been opened, attaching the driver to the current session.
The code I'm using, which works in part, is:
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
service = Service('C:\\Users\\nicoc\\PycharmProjects\\WriteAI\\chromedriver.exe')
driver = webdriver.Chrome(service=service)
executor_url = driver.command_executor._url
session_id = driver.session_id
driver = attach_to_session(executor_url, session_id)
It works in part because, it correctly open a new browser window and start navigating according to my code, with an already existing Chrome session open, but it won't use the Chrome profile the already opened session is using.
Also, an even better solution would be to open the driver with a new tab on the already opened Chrome window, instead of opening a new Chrome Window when launching the driver.
I can still manage that the driver opens a new Chrome window, as soon as it uses the specific profile that it's in use on the active Chrome session.
I have already tried to add the option arguments with
driver = webdriver.Chrome(service=service, options=chrome_options)
chrome_options = Options()
chrome_options.add_argument\
(r"--user-data-dir=C:\\Users\\nicoc\\AppData\\Local\\Google\\Chrome\\User Data")
chrome_options.add_argument(r'--profile-directory=Default')
but I got an error saying the profile is already in use
EDIT using the driver.get("https://www.youtube.com/")
while a chrome instance is open returns the error below:
selenium.common.exceptions.InvalidArgumentException: Message: invalid argument: user data directory is already in use, please specify a unique value for --user-data-dir argument, or don't use --user-data-dir
if I remove the option
chrome_options.add_argument(r"--user-data-dir=C:\\Users\\nicoc\\AppData\\Local\\Google\\Chrome\\User Data")
it opens a new Chrome window but, again, with no profile loaded