Files
google-cookie-retrieval/selenium_cookie_extractor_json.py
2025-02-17 12:24:22 -08:00

70 lines
2.5 KiB
Python

#!/usr/bin/env python3
import time
import json
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
# Configure Chrome options to run in incognito mode.
options = webdriver.ChromeOptions()
options.add_argument("--incognito")
# Uncomment the following option if you want to auto-open developer tools for each tab.
# options.add_argument("--auto-open-devtools-for-tabs")
# Initialize the Chrome driver.
# If ChromeDriver is not in your PATH, specify its location: Service('/path/to/chromedriver')
service = Service() # Assumes chromedriver is in your PATH
driver = webdriver.Chrome(service=service, options=options)
print("Opening https://chat.google.com ...")
driver.get("https://chat.google.com")
print("\nA new incognito window has been opened.")
print("Please log in normally. To inspect cookies manually:")
print(" 1. Press F12 to open developer tools.")
print(" 2. Navigate to the Application (Chrome) or Storage (Firefox) tab.")
print(" 3. Expand Cookies and select https://chat.google.com.")
print(" 4. Verify that the COMPASS, SSID, SID, OSID, and HSID cookies are present.")
print("\nIMPORTANT: Once you are logged in and have confirmed the cookies (or just logged in),")
print("press Enter here. (Remember: to keep the validity of these cookies, close the browser soon!)")
input("Press Enter to extract cookies...")
# Navigate to some invalid URL on chat.google.com. This way we won't be redirected back to a
# mail.google.com page and this allows us to extract the correct cookies.
driver.get("https://chat.google.com/u/0/mole/world")
# Get all cookies
all_cookies = driver.get_cookies()
# Define the cookie names we want (case-insensitive)
target_names = {"COMPASS", "SSID", "SID", "OSID", "HSID"}
extracted = {}
# For COMPASS cookie, if multiple are present, prefer the one with path == "/"
compass_cookie = None
for cookie in all_cookies:
name_upper = cookie["name"].upper()
if name_upper not in target_names:
continue
if name_upper == "COMPASS":
if cookie.get("path", "") == "/":
compass_cookie = cookie
elif compass_cookie is None:
compass_cookie = cookie
else:
extracted[name_upper] = cookie["value"]
if compass_cookie:
extracted["COMPASS"] = compass_cookie["value"]
# Form JSON object of the extracted cookies.
json_data = json.dumps(extracted, indent=2)
print("\nExtracted Cookie JSON:")
print(json_data)
print("\nClosing the browser window to avoid invalidating the cookies (Google uses refresh tokens).")
# Close the browser window.
driver.quit()