解决 yt-dlp 使用的 cookies 文件格式的问题

问题

使用 yt-dlp 下载时遇到了这样的问题:

$ yt-dlp http://xxx

[xxx] Extracting URL: xxx xxx
[xxx] xxx: Downloading webpage
ERROR: [xxx] xxx: Unable to download webpage: HTTP Error 412: Precondition Failed
(caused by <HTTPError 412: Precondition Failed>)

经过搜索,发现需要登录验证,或者提供 cookies 才可以。

使用 cookies.txt 方法

(1) 通过浏览器找到 cookies

比如 Chrome 浏览器,按 F12 进入 Application,从左侧 Storage 里找到所需要的 cookies,拷贝并保存下来。

(2) 转换格式

如果直接使用的话会报错,提示文件格式问题:

$ yt-dlp --cookies cookies.txt http://xxx

... ...
ERROR: 'cookies.txt' does not look like a Netscape format cookies file
... ...

所以需要转换到所要求的 Netscape format,大概过程可参考后面的代码。

(3) 下载

$ yt-dlp --cookies cookies.txt http://xxx
...

完成。

格式转换

from datetime import datetime

class CookieFormatter:
    def __init__(self, text: str) -> None:
        items = list(text.split())
        self.name = items[0]
        self.value = items[1]
        self.domain = items[2]
        self.path = items[3]
        self.expires = items[4]
        self.size = items[5]
        self.priority = items[6]

    def __repr__(self) -> str:
        text = ''
        text += self.domain + '\t'
        text += 'TRUE\t'
        text += self.path + '\t'
        text += 'FALSE\t'
        if self.expires == 'Session':
            text += '0\t'
        else:
            d = datetime.fromisoformat(self.expires)
            text += '{}\t'.format(int(d.timestamp()))
        text += self.name + '\t'
        text += self.value + '\t'

        return text.strip()


def main() -> int:
    print('# Netscape HTTP Cookie File')
    print('# http://curl.haxx.se/rfc/cookie_spec.html')
    print('# This is a generated file!  Do not edit.')
    print()

    with open('a.txt') as f:
        for line in f:
            print(CookieFormatter(line))

    return 0

Read More: