pythonpython-2.7user-agentyoutube-dl

Custom User-Agent in youtube-dl python script


I have the following piece of python code which calls youtube-dl and extracts the links that I need.

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

But I want to use the custom User-Agent in this program. I know I can specify the custom User-Agent while using the youtube-dl in the command line.

Is there any way I can specify the custom user-agent in the program embedding youtube-dl.

Thanks


Solution

  • I used Github's code search to find user-agent in the YTDL codebase, ended up finding this piece of code that sets the user agent based on the command line.

    So, all in all, just

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

    to override it.