[Python] Selenium (Chrome 136): "Failed to decrypt" errors with copied profile prevent use of...

Discussão em 'Python' iniciado por Stack, Maio 11, 2025.

  1. Stack

    Stack Membro Participativo

    I'm trying to automate Google Chrome 136 using Selenium 4.25.0 in Python to access https://aistudio.google.com using my existing, logged-in "Default" Google Chrome profile.

    Previously, I was facing an issue where Selenium would launch Chrome with my profile (showing my "New Tab" page) but would not navigate away from chrome://newtab/ when driver.get() was called.

    Based on excellent advice from @Ajeet Verma (Selenium 4.25 opens Chrome 136 with existing profile to "New Tab" instead of navigating with driver.get()), I tried the "copied profile" method:

    Ensured Chrome was fully closed (all chrome.exe processes terminated).

    Created a new directory (e.g., C:\SeleniumChromeProfiles\MyAutomationProfile).

    Copied my entire original profile (%LOCALAPPDATA%\Google\Chrome\User Data\Default) into a Default subfolder within that new directory (so, C:\SeleniumChromeProfiles\MyAutomationProfile\Default...).

    Updated my Selenium script to use:

    chrome_options.add_argument(f"--user-data-dir=C:\\SeleniumChromeProfiles\\MyAutomationProfile")
    # And importantly, I OMITTED chrome_options.add_argument("--profile-directory=Default")


    Current Situation & New Problem:

    When I run the script with this copied profile setup:

    Chrome launches, and it seems to recognize the copied profile data (e.g., it initially goes to my "New Tab" page, chrome://new-tab-page-third-party/ in my case).

    However, the Chrome console (and my script's output) is now flooded with errors like:

    [<PID>:<TID>:MMDD/HHMMSS.XXX:ERROR:components\os_crypt\sync\os_crypt_win.cc:105] Failed to decrypt: 鞈?銝迤蝣箝?(0xD)


    (The gibberish text might vary, but the os_crypt_win.cc:105] Failed to decrypt part is consistent).

    Crucially, although the browser opens with some profile elements, it does not have my active Google login session for AI Studio. If I then try to navigate to https://aistudio.google.com, it requires me to sign in again.

    This indicates that while the profile files were copied, the sensitive data within them (like authentication cookies/tokens) cannot be decrypted by this new Chrome instance launched by Selenium using the copied profile. This defeats my goal of using a pre-existing, already authenticated session without manual re-login for each automation run.

    Environment:

    OS: Windows 11 Pro, Version 23H2

    Python Version: 3.12.x

    Selenium Version: 4.25.0

    Chrome Browser Version: 136.0.7103.93 (Official Build) (64-bit)

    ChromeDriver Version: 136.0.7103.xx (for win64)

    Simplified Code for Launching with Copied Profile: (Use the same simplified setup_driver and main from the previous Stack Overflow draft, just ensure CHROME_PROFILE_USER_DATA_DIR points to your new copied profile's parent directory, e.g., C:\SeleniumChromeProfiles\MyAutomationProfile, and that the --profile-directory argument is omitted in chrome_options.)

    import time
    import os
    from selenium import webdriver
    from selenium.webdriver.chrome.service import Service
    from selenium.webdriver.chrome.options import Options
    from selenium.common.exceptions import WebDriverException

    # --- Configuration ---
    CHROME_DRIVER_PATH = r'C:\Users\stat\Downloads\chromedriver-win64\chromedriver-win64\chromedriver.exe' # My actual path
    # Path to the PARENT of the COPIED "Default" profile
    CHROME_COPIED_PROFILE_PARENT_DIR = r'C:\SeleniumChromeProfiles\MyAutomationProfile' # Example - I created this and xcopied ...\User Data\Default into ...\MyAutomationProfile\Default

    TARGET_URL = "https://aistudio.google.com/prompts/new_chat"

    def setup_driver():
    print(f"Driver Path: {CHROME_DRIVER_PATH}")
    print(f"User Data Dir (for copied profile): {CHROME_COPIED_PROFILE_PARENT_DIR}")

    if not os.path.exists(CHROME_DRIVER_PATH):
    print(f"FATAL: ChromeDriver not found: '{CHROME_DRIVER_PATH}'.")
    return None
    if not os.path.isdir(CHROME_COPIED_PROFILE_PARENT_DIR):
    print(f"FATAL: Copied profile parent dir not found: '{CHROME_COPIED_PROFILE_PARENT_DIR}'.")
    return None
    if not os.path.isdir(os.path.join(CHROME_COPIED_PROFILE_PARENT_DIR, "Default")):
    print(f"FATAL: 'Default' subfolder NOT found inside '{CHROME_COPIED_PROFILE_PARENT_DIR}'. Profile copy likely incorrect.")
    return None

    chrome_options = Options()
    # Key part for copied profile method: point to the new parent directory
    chrome_options.add_argument(f"--user-data-dir={CHROME_COPIED_PROFILE_PARENT_DIR}")
    # DO NOT use --profile-directory, Chrome will look for "Default" inside the user-data-dir

    chrome_options.add_experimental_option("excludeSwitches", ["enable-automation", "load-extension"])
    chrome_options.add_experimental_option('useAutomationExtension', False)
    prefs = {
    "credentials_enable_service": False,
    "profile.password_manager_enabled": False
    }
    chrome_options.add_experimental_option("prefs", prefs)
    chrome_options.add_argument("--disable-extensions")
    chrome_options.add_argument("--start-maximized")

    try:
    service = Service(executable_path=CHROME_DRIVER_PATH)
    driver = webdriver.Chrome(service=service, options=chrome_options)
    print("WebDriver initialized with copied profile settings.")
    return driver
    except WebDriverException as e:
    print(f"FATAL WebDriverException during setup: {e}")
    return None
    except Exception as e_setup:
    print(f"Unexpected FATAL error during setup: {e_setup}")
    return None

    def main():
    print("IMPORTANT: Ensure ALL Google Chrome instances are FULLY CLOSED before running this script.")
    input("Press Enter to confirm and continue...")

    driver = setup_driver()
    if not driver:
    print("Driver setup failed. Exiting.")
    return

    try:
    print(f"Browser launched. Waiting a moment...")
    print(f"Initial URL: '{driver.current_url}', Initial Title: '{driver.title}'")
    time.sleep(4)

    print(f"Attempting to navigate to: {TARGET_URL}")
    driver.get(TARGET_URL)
    print(f"Called driver.get(). Waiting for navigation...")
    time.sleep(7) # Allow time for navigation / login redirect

    current_url_after_get = driver.current_url
    print(f"After 7s wait - Current URL: '{current_url_after_get}', Title: '{driver.title}'")

    if "accounts.google.com" in current_url_after_get:
    print("RESULT: Navigated to a Google login/account page. Copied session was not active/decrypted.")
    elif TARGET_URL in current_url_after_get:
    print("RESULT: Potentially successful navigation to AI Studio (but still check if login is required on page).")
    else:
    print(f"RESULT: Navigation FAILED. Browser is on '{current_url_after_get}'.")

    except Exception as e:
    print(f"An error occurred: {e}")
    finally:
    print("Script finished or errored.")
    input("Browser will remain open. Press Enter to close...")
    if driver:
    driver.quit()

    if __name__ == "__main__":
    if not os.path.exists(CHROME_COPIED_PROFILE_PARENT_DIR) or \
    not os.path.isdir(os.path.join(CHROME_COPIED_PROFILE_PARENT_DIR, "Default")):
    print("ERROR: The copied profile directory setup seems incorrect.")
    print(f"Ensure '{CHROME_COPIED_PROFILE_PARENT_DIR}' exists AND contains a 'Default' subfolder with your copied profile data.")
    else:
    main()


    My Question for Stack Overflow:

    The ERROR:components\os_crypt\sync\os_crypt_win.cc:105] Failed to decrypt errors strongly suggest that the copied profile's encrypted data (cookies, session tokens for Google) cannot be decrypted by the new Chrome instance launched by Selenium. This results in needing to log in again, defeating the purpose of using the copied profile to maintain an existing session.

    Is there a way to make this "copied profile" approach work with Selenium on Windows such that the encrypted session data is successfully decrypted and used, avoiding a manual re-login? (Perhaps specific Chrome flags or an interaction with Windows DPAPI that Selenium can influence?)

    If direct decryption of a copied profile is generally not feasible for Google accounts due to security, what is the most reliable alternative strategy for fully unattended Selenium automation that requires a persistent Google login, other than scripting the entire login process itself (which is complex with 2FA)?

    Do the persistent "Failed to decrypt" errors, even if a login page is subsequently handled, indicate any underlying instability or unreliability for the browser session that Selenium is controlling?

    I'm trying to avoid scripting the login flow manually if there's a more direct way to leverage a profile (original or copied) while respecting Chrome's security mechanisms for automation.

    Continue reading...

Compartilhe esta Página