youtube-dl python 脚本中的自定义用户代理

Custom User-Agent in youtube-dl python script

我有以下一段 python 代码,它调用 youtube-dl 并提取我需要的链接。

ydl = youtube_dl.YoutubeDL({'outtmpl': '%(id)s%(ext)s'})

with ydl:
    result = ydl.extract_info(
        url,
        download=False
         # We just want to extract the info
    )

if 'entries' in result:
    # Can be a playlist or a list of videos
    video = result['entries'][0]
else:
    # Just a video
    video = result

if video:
    return video

return None

但是我想在这个程序中使用自定义的User-Agent。我知道我可以在命令行中使用 youtube-dl 时指定自定义用户代理。

有什么方法可以在嵌入 youtube-dl 的程序中指定自定义用户代理。

谢谢

我使用 Github 的代码搜索在 YTDL 代码库中找到 user-agent,最终找到 this piece of code,它根据命令行设置用户代理。

所以,总而言之,只是

import youtube_dl.utils
youtube_dl.utils.std_headers['User-Agent'] = 'my-user-agent'

覆盖它。