Search code examples
pythonselenium-webdriverselenium-chromedriver

Unable to interact with selenium webdriver after initializing it with the new service method [Python]


I'm trying to initialize a chrome webdriver with a custom user profile using the following code:

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service

options = webdriver.ChromeOptions()
options.add_experimental_option("detach", True)
options.add_argument("--start-maximized")
options.add_argument(r'user-data-dir=C:\Users\{User}\AppData\Local\Google\Chrome\User Data\Profile XY')
service = Service(executable_path=r'C:\Program Files\Google\Chrome\Application\chrome.exe')
driver = webdriver.Chrome(options=options, service=service)

So far so good. Up until this point the code is executed and a new Chrome window pops up with the correct user profile selected. However, everything that comes after the initialization of the webdriver isn't executed anymore. E.g. the following code won't be executed.

print("This is a debug msg")
driver.get("https://google.com/")

So my question is, how do i properly interact with the driver after it has been initialized if i cannot use driver.doSomething() anymore?

Any help would be appreciated.

Additional info: using the newest chrome and selenium versions.

See the above code example.


Solution

  • service = Service(executable_path=r'C:\Program Files\Google\Chrome\Application\chrome.exe')
    

    Above is incorrect. You need to supply full path of chromedriver.exe not chrome.exe in executable_path

    Alternate solution: You don't need to set the chromedriver.exe manually anymore. If you are using latest selenium(v4.6.0 or above), you can skip setting path in the executable_path. See code below:

    from selenium import webdriver
    from selenium.webdriver.chrome.service import Service
    
    options = webdriver.ChromeOptions()
    options.add_experimental_option("detach", True)
    options.add_argument("--start-maximized")
    options.add_argument(r'user-data-dir=C:\Users\{User}\AppData\Local\Google\Chrome\User Data\Default')
    service = Service()
    driver = webdriver.Chrome(options=options, service=service)
    print("This is a debug msg")
    driver.get("https://google.com/")
    

    Console result:

    This is a debug msg
    
    Process finished with exit code 0
    

    Refer this answer for more info - https://stackoverflow.com/a/76463081/7598774