Having trouble reading and writing cookies?

Posted by ThoseDistantMemories@reddit | learnprogramming | View on Reddit | 1 comments

I'm trying to create a script that (A) uses an existing cookies file, cookies.txt (generated using the command yt-dlp --cookies-from-browser chrome -o cookies.txt "https://www.youtube.com/watch?v=dQw4w9WgXcQ" ), to auto-sign into youtube when the url is opened, (B) extract new cookies from the site, then (C) rewrite cookies.txt with those new cookies. However, I continuously get this error: Cookie refresh failed: 'utf-8' codec can't decode byte 0xe2 in position 44: invalid continuation byte. What is going wrong?

Furthermore, even when I try directly using the cookies.txt file generated by ytdlp to run another ytdlp command, I get this error:

ERROR in app: Download failed: Download failed: Command 'yt-dlp -f bestaudio --extract-audio --audio-format mp3 -o "./static/music\b0085c6b-8bea-4b2c-8adf-1dea04d0bd5a\%(title)s.%(ext)s" --ffmpeg-location "ffmpeg-master-latest-win64-gpl-shared\bin\ffmpeg.exe" --cookies "cookies.txt" "https://youtu.be/gWxLanshXw4?si=SFQzXdRhkO-LDiZ4"' returned non-zero exit status 1.

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service
import os

def refresh_youtube_cookies(cookies_file="cookies.txt"):
    chrome_options = Options()
    chrome_options.add_argument("--headless")

    script_dir = os.path.dirname(os.path.abspath(__file__))
    chromedriver_path = os.path.join(script_dir, "chromedriver", "chromedriver-win64", "chromedriver.exe")

    if not os.path.exists(chromedriver_path):
        print(f"Error: ChromeDriver not found at {chromedriver_path}")
        return

    service = Service(executable_path=chromedriver_path)
    driver = webdriver.Chrome(service=service, options=chrome_options)

    try:
        # Load cookies from file with UTF-8 encoding
        if os.path.exists(cookies_file):
            with open(cookies_file, "r", encoding="utf-8") as f: #added encoding = "utf-8"
                for line in f:
                    try:
                        name, domain, path, secure, expiry, value = line.strip().split("\t")
                        secure = secure.lower() == "true"
                        if expiry:
                            expiry = int(expiry)
                        driver.add_cookie({
                            "name": name,
                            "domain": domain,
                            "path": path,
                            "secure": secure,
                            "expiry": expiry if expiry else None,
                            "value": value,
                        })
                    except ValueError:
                        print(f"Warning: Invalid cookie line: {line.strip()}")

        # Navigate to YouTube
        driver.get("https://www.youtube.com/")

        # Extract and save cookies with UTF-8 encoding
        cookies = driver.get_cookies()
        with open(cookies_file, "w", encoding="utf-8") as f: #added encoding = "utf-8"
            for cookie in cookies:
                f.write(f"{cookie['name']}\t{cookie['domain']}\t{cookie['path']}\t{cookie['secure']}\t{cookie.get('expiry', '')}\t{cookie['value']}\n".encode('utf-8', errors='replace').decode('utf-8'))
        print(f"YouTube cookies refreshed and saved to {cookies_file}.")

    except Exception as e:
        print(f"Cookie refresh failed: {e}")
    finally:
        driver.quit()

refresh_youtube_cookies()