browser-cookie3

0.20.1 · active · verified Tue Apr 14

browser-cookie3 is a Python library that loads cookies from various web browsers (Chrome, Firefox, Edge, Safari, Opera, Brave, etc.) into a `cookiejar` object. This enables Python programs, often used for web scraping or automation, to download content as seen in a web browser without needing to re-authenticate. The library is actively maintained, with frequent updates to support new browser versions and address changes in cookie storage mechanisms.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to load cookies from a specific browser (e.g., Chrome) and then use them with the popular `requests` library to access a website as if you were logged in. The `domain_name` argument is optional but recommended for performance and security. Replace 'example.com' with the target domain.

import browser_cookie3
import requests
import os

def get_cookies_for_requests(browser_function):
    """Gets cookies from a specified browser function and returns a requests.cookies.RequestsCookieJar."""
    try:
        # The specific browser function (e.g., browser_cookie3.chrome())
        # returns a http.cookiejar.CookieJar object.
        cj = browser_function(domain_name='example.com') # Filter for a specific domain for efficiency
        return cj
    except Exception as e:
        print(f"Error loading cookies from {browser_function.__name__}: {e}")
        return None

# Example: Get cookies from Chrome and use them with requests
# Make sure you are logged into 'example.com' in Chrome before running.
chrome_cookies = get_cookies_for_requests(browser_cookie3.chrome)

if chrome_cookies:
    print(f"Successfully loaded {len(list(chrome_cookies))} cookies from Chrome.")
    # Use the cookies with the requests library
    # Replace 'https://example.com' with the actual URL you want to access
    # Ensure the URL matches the domain for which cookies were loaded.
    try:
        response = requests.get('https://example.com', cookies=chrome_cookies)
        response.raise_for_status() # Raise an HTTPError for bad responses (4xx or 5xx)
        print(f"Successfully fetched page from example.com. Status code: {response.status_code}")
        # print(response.text[:500]) # Print first 500 characters of the content
    except requests.exceptions.RequestException as e:
        print(f"Request failed: {e}")
else:
    print("Could not load cookies from Chrome. Make sure Chrome is running and you are logged in.")

# You can also try other browsers:
# firefox_cookies = get_cookies_for_requests(browser_cookie3.firefox)
# if firefox_cookies:
#     print(f"Loaded {len(list(firefox_cookies))} cookies from Firefox.")

view raw JSON →