Skip to content
Advertisement

Get URL of downloaded video in youtube_dl progress hook

How can I get the URL of a video that I’m downloading using youtube_dl?

I can use progress hooks to get other characteristics of the download, like the file path:

def progress_hook(response):
    if response["status"] == "finished":
        file_name = response["filename"]

ydl_opts = {
    'progress_hooks': [progress_hook]
}

I also want to get the URL that the file came from. I can’t figure out how to do that. Something like url = response["url"] would be good, but there aren’t very many options with progress hooks.

Advertisement

Answer

Since there doesn’t seem to be a way to do this, I restructured my program to only download one at a time, so it was very explicit to me which was being downloaded.

To use this, you create an instance of it, passing the list of URLs you want to download to the constructor.

Then, when you’re ready, you can call start_download_process on the object. It will wait until the current track is finished and the progress_hook is fully done before downloading another.

class YoutubeManager:
    def __init__(self, url_list):
        self.base_url = "https://www.youtube.com"
        self.current_download_url = ""
        self.url_list = url_list

        self.currently_downloading = False
        self.current_download_count = 0

        ydl_opts = {
            'format': 'bestaudio/best',
            'noplaylist': True,
            'continue_dl': True,
            'progress_hooks': [self.progress_hook],
            'postprocessors': [{
                'key': 'FFmpegExtractAudio',
                'preferredcodec': 'mp3',
                'preferredquality': '192', }]
        }

        self.youtube_dl_manager = youtube_dl.YoutubeDL(ydl_opts)
        

    def start_download_process(self):
        self.currently_downloading = True
        self.current_download_count += 1

        with self.youtube_dl_manager as youtube_dl_manager:
            self.current_download_url = self.url_list.pop()
            youtube_dl_manager.download([self.base_url + self.current_download_url])

    def continue_download_process(self):
        self.current_download_count += 1
        with self.youtube_dl_manager as youtube_dl_manager:
            self.current_download_url = self.url_list.pop()
            youtube_dl_manager.download([self.base_url + self.current_download_url])

    def progress_hook(self, response):
        if response["status"] == "finished":
            file_name = response["filename"]
            print("Downloaded " + file_name)

            # You can do something with self.current_download_url and file_name here

            if len(self.url_list) != 0:
                self.continue_download_process()
            else:
                self.currently_downloading = False
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement