0

I am trying to automate Chrome using Selenium by creating a new Chrome profile, copying the contents of the Default profile, and launching it with Selenium to retrieve cookies. However, I keep encountering the following error:

selenium.common.exceptions.SessionNotCreatedException: Message: session not created
from chrome not reachable

Full Traceback

Traceback (most recent call last):
  File "test.py", line 71, in g_chrome_cookies
    driver = webdriver.Chrome(service=service, options=options)
  File "C:\Users\Securely\AppData\Local\Programs\Python\Python39\lib\site-packages\selenium\webdriver\chrome\webdriver.py", line 45, in __init__
    super().__init__(
  File "C:\Users\Securely\AppData\Local\Programs\Python\Python39\lib\site-packages\selenium\webdriver\chromium\webdriver.py", line 66, in __init__
    super().__init__(command_executor=executor, options=options)
  File "C:\Users\Securely\AppData\Local\Programs\Python\Python39\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 250, in __init__
    self.start_session(capabilities)
  File "C:\Users\Securely\AppData\Local\Programs\Python\Python39\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 342, in start_session
    response = self.execute(Command.NEW_SESSION, caps)["value"]
  File "C:\Users\Securely\AppData\Local\Programs\Python\Python39\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 429, in execute
    self.error_handler.check_response(response)
  File "C:\Users\Securely\AppData\Local\Programs\Python\Python39\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 232, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.SessionNotCreatedException: Message: session not created
from chrome not reachable

Additionally, I also tried using --remote-debugging-pipe, but it results in a timeout error.

Environment:

OS: Windows 10 / 11 (tested on three machines)

Chrome Version: 136.0.7103.93 (64-bit)

ChromeDriver Version: 4.0.2 (managed by webdriver-manager)

Selenium Version: 4.31.0

Python Version: 3.9.5

I have tested this on three different Windows machines, and the error is identical on all of them.

Code

import os
import shutil
import getpass
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
from traceback import format_exc

def copy_profile():
    """Copy Chrome 'Default' profile to a new profile folder 'Profile X' where X is the next available number."""
    username = getpass.getuser()
    base_path = rf"C:\Users\{username}\AppData\Local\Google\Chrome\User Data"
    src_path = os.path.join(base_path, "Default")
    
    # Find next available Profile number
    for i in range(1, 100):
        dest_path = os.path.join(base_path, f"Profile {i}")
        if not os.path.exists(dest_path):
            break
    
    print(f"Copying profile from:\n  {src_path}\nto:\n  {dest_path}")
    shutil.copytree(src_path, dest_path)
    return dest_path

def g_chrome_cookies(profile_name):
    """Launch Chrome with a specific profile and get cookies from Facebook."""
    username = getpass.getuser()
    user_data_dir = rf"C:\Users\{username}\AppData\Local\Google\Chrome\User Data"
    
    if not os.path.exists(user_data_dir):
        raise FileNotFoundError(f"Chrome user data directory not found: {user_data_dir}")
    
    options = Options()
    options.add_argument("--disable-gpu")
    options.add_argument("--disable-software-rasterizer")
    options.add_argument("--disable-dev-shm-usage")
    options.add_argument("--no-sandbox")
    options.add_argument("--disable-extensions")
    # options.add_argument('--remote-debugging-pipe')  # I have checked this option but it causes a timeout error
    options.add_argument(f"user-data-dir={user_data_dir}")
    options.add_argument(f'--profile-directory={profile_name}')
    # Uncomment the next line if you want headless mode
    # options.add_argument("--headless=new")
    
    os.environ["QT_LOGGING_RULES"] = "qt.sql.sqlite.warning=false"
    service = Service(ChromeDriverManager().install())
    
    driver = None
    try:
        driver = webdriver.Chrome(service=service, options=options)
        driver.get("https://www.facebook.com/")
        cookies = driver.get_cookies()
        return {cookie['name']: cookie['value'] for cookie in cookies}
    except Exception:
        print(format_exc())
        return {}
    finally:
        if driver:
            driver.quit()

def generate_cookies():
    print("[+] Creating new Chrome profile")
    new_profile_path = copy_profile()
    
    try:
        profile_number = new_profile_path.split("Profile")[-1].strip()
        profile_name = f"Profile {profile_number}"
        cookies = g_chrome_cookies(profile_name)
        print("[+] Retrieved cookies:", cookies)
    except Exception:
        print(format_exc())
    finally:
        print("[+] Deleting the copied profile folder")
        if os.path.exists(new_profile_path):
            shutil.rmtree(new_profile_path)

if __name__ == "__main__":
    generate_cookies()

What I have tried:

  • Using different profile names
  • Adding --remote-debugging-pipe (results in timeout)
  • Ensuring the user data directory exists and is accessible
  • Running on multiple machines with same Chrome and ChromeDriver versions
3
  • this won't work in more recent versions of Chrome. (the encryption has changed to per app/folder) Instead you should just use a fresh profile (by default the driver already does that, so no need to set profile or user-data-dir...) and then login using your script to enter proper credentials. Commented May 19 at 20:58
  • I can not load the actual profile too (without making any copy). Also, I don't have the credentials and I must achieve loading cookies Commented May 22 at 8:57
  • I think the only option would be to rollback to an earlier version of Chrome (pre-v136). (that would make the new cookies un-readable, though, as they would be saved with a different encryption key) Use environment variable for "webdriver.chrome.disableBuildCheck", "true" if using a different version of Chromedriver. Commented May 22 at 17:37

1 Answer 1

0

I know I'm late but there's probably still people out there facing the same issue. Loading cookies or your own user profile isn't working at all since chrome updated to 137. version

Best you can do is downgrade your chrome and hold the package to avoid auto updating it.

Down below is everything you need in order to fix it (Linux

# Delete current version of chrome
sudo apt remove -y google-chrome-stable --allow-change-held-packages

# Download and install old version of chrome / Hold chrome version
cd tmp
wget -c https://mirror.cs.uchicago.edu/google-chrome/pool/main/g/google-chrome-stable/google-chrome-stable_134.0.6998.165-1_amd64.deb
sudo dpkg -i google-chrome-stable_134.0.6998.165-1_amd64.deb
sudo apt -f install -y
sudo apt-mark hold google-chrome-stable

# Also download the correct chromedriver and install it
sudo rm -f /usr/local/bin/chromedriver
wget -c https://storage.googleapis.com/chrome-for-testing-public/134.0.6998.165/linux64/chromedriver-linux64.zip
unzip chromedriver-linux64.zip
sudo mv chromedriver-linux64/chromedriver /usr/local/bin/
sudo chmod +x /usr/local/bin/chromedriver

For undetected_chromedriver:

driver = uc.Chrome(driver_executable_path="/usr/local/bin/chromedriver", version_main=134, use_subprocess=True)

Edit: You can still use your own chrome profile, just copy it from your chrome location into another location 🤞

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.