Search code examples
pythoncookiesbrowser

Get Browser Cookies Universally in Python


ive been searching for an hour now and cant find a solution. plan is to use python and print the cookies in plaintext format. i know that the chrome cookies are encrypted.

i tried to use over scripts but they either said permission denied(i also tried to run as admin but didnt work) or couldnt find table or file.

plan is to make it work on all browsers including edge, chrome, firefox, brave and all other chromium based browsers.

script i tried using:

import os
import sqlite3

def get_chrome_cookies():
    # Local sqlite Chrome cookie database path
    db_path = os.path.join(os.environ["USERPROFILE"], "AppData", "Local",
                           "Google", "Chrome", "User Data", "Default", "Cookies")

    if not os.path.isfile(db_path):
        print(f"Chrome cookie database not found at: {db_path}")
        return []

    try:
        # Connect to the database
        db = sqlite3.connect(db_path)
        cursor = db.cursor()

        # Get the cookies from the `cookies` table
        cursor.execute("""
        SELECT host_key, name, value, creation_utc, last_access_utc, expires_utc
        FROM cookies
        """)
        
        cookies = []

        for row in cursor.fetchall():
            host_key, name, value, creation_utc, last_access_utc, expires_utc = row
            cookies.append({
                'Host': host_key,
                'Name': name,
                'Value': value,
                'Creation datetime (UTC)': creation_utc,
                'Last access datetime (UTC)': last_access_utc,
                'Expires datetime (UTC)': expires_utc
            })

        # Close connection
        db.close()

        return cookies

    except sqlite3.Error as e:
        print(f"SQLite error: {e}")
        return []

if __name__ == "__main__":
    chrome_cookies = get_chrome_cookies()

    for cookie in chrome_cookies:
        print(f"""
        Host: {cookie['Host']}
        Cookie name: {cookie['Name']}
        Cookie value: {cookie['Value']}
        Creation datetime (UTC): {cookie['Creation datetime (UTC)']}
        Last access datetime (UTC): {cookie['Last access datetime (UTC)']}
        Expires datetime (UTC): {cookie['Expires datetime (UTC)']}
        ===============================================================
        """)


Solution

  • I don't know, how your sqlite table looks like. But if you are interested of the brpwser cookies you can do:

    import requests
    import browser_cookie3
    import http.cookiejar
    
    cj = browser_cookie3.chrome()
    r = requests.get("https://google.com", cookies=cj)
    
    cookies = list(cj)
    
    for cookie in cj:
       print("\nName:", cookie.name,
             "\nValue:", cookie.value,
             "\nDomän:", cookie.domain)
    
    print("\nAmount of cookies:", len(cj)) 
    

    Or without third party module:

    import requests
    import pprint
    
    session = requests.Session()
    r = session.get("https://google.com")
    cookie = session.cookies.get_dict()
    
    pp = pprint.PrettyPrinter()
    pp.pprint(cookie)