Search code examples
pythonyoutube-dlyt-dlp

how do I skip a private video, with this python code


the Package how do I skip a private video with this code I tried the optons (rejecttitle ignore-errors) I looked at YoutubeDL.py at github for option and i have no access to the video is of a Playlist

from __future__ import unicode_literals

from datetime import datetime
import os
import shutil
import sys
import time
import traceback
from os import system, name

import yt_dlp as yb

with open("location.txt", 'w+t') as s:
    s.write(input("path to save files: "))
    s.seek(0)
    data = s.read()
    print("thumbnails will be moved to " + data + "\\thumbnail")


def run():
    while True:
        video_url = input("\nplease enter youtube video url: ")
        video_info = yb.YoutubeDL().extract_info(
            url=video_url, download=False)
        filename = f"{video_info['title']}"

        ydl_opts = {
            'format': 'bestvideo[ext=mp4]+bestaudio[ext=m4a]/bestvideo+bestaudio/best',
            'download_archive': 'downloaded_songs.txt',
            'windowsfilenames': True,
            'outtmpl': data + '/%(title)s.%(ext)s',
            'writesubtitles': True,
            'subtitleslangs': ['en', '-live_chat'],
            'writethumbnail': True,
            'embedthumbnail': True,
            'abort_on_unavailable_fragments': False,
            'ignoreerrors': True,
            'verbose': True,
            'postprocessors': [
                {'key': 'FFmpegMetadata',
                 'add_metadata': True, },
                {'key': 'FFmpegEmbedSubtitle'},
                {'key': 'EmbedThumbnail',
                 'already_have_thumbnail': True,
                 },
            ]
        }

        with yb.YoutubeDL(ydl_opts) as ydl:
            ydl.download([video_info['webpage_url']])
            print("\nDownload complete... {}".format(filename))
            thumbnail_path()
            clear()


def thumbnail_path():
    start_time = datetime.now()
    sourcepath = data
    sourcefiles = os.listdir(sourcepath)
    destinationpath = data + '/thumbnail'
    thumbnail = os.path.exists(destinationpath)
    if not thumbnail:
        os.makedirs(destinationpath)
    for file in sourcefiles:
        if file.endswith('.webp'):
            shutil.move(os.path.join(sourcepath, file), os.path.join(destinationpath, file))
    end_time = datetime.now()
    print('Duration: {}'.format(end_time - start_time))


def close():
    time.sleep(0)
    print('\nBye')
    time.sleep(1)
    sys.exit()


def clear():
    while True:
        ans = input("\nDo you want to start again? (y/n) ")
        if ans.lower() == "y":
            if name == "nt":
                system('cls')
                time.sleep(0)
                run()

            else:
                system('clear')
                time.sleep(0)
                run()

        elif ans.lower() == 'n':
            if name == 'nt':
                system('cls')
                close()

            else:
                system('clear')
                close()
        else:
            print("Please respond with 'Yes' or 'No'\n")


if __name__ == '__main__':
    try:
        run()
    except KeyboardInterrupt:
        print('\nInterrupted')
        while True:
            clear()
    except Exception:
        with open("log.txt", "w") as log:
            traceback.print_exc(file=log)
            print('\nError is printed to log.txt')
            close()

ERROR: [youtube] FvnQJZnnXXo: Private video. Sign in if you've been granted access to this video

Output from log,txt

Traceback (most recent call last):
  File "C:\Users\User\PycharmProjects\YouTube-\venv\lib\site-packages\yt_dlp\extractor\common.py", line 640, in extract
    ie_result = self._real_extract(url)
  File "C:\Users\User\PycharmProjects\YouTube-\venv\lib\site-packages\yt_dlp\extractor\youtube.py", line 3477, in _real_extract
    self.raise_no_formats(reason, expected=True)
  File "C:\Users\User\PycharmProjects\YouTube-\venv\lib\site-packages\yt_dlp\extractor\common.py", line 1124, in raise_no_formats
    raise ExtractorError(msg, expected=expected, video_id=video_id)
yt_dlp.utils.ExtractorError: Private video. Sign in if you've been granted access to this video

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\User\PycharmProjects\YouTube-\venv\lib\site-packages\yt_dlp\YoutubeDL.py", line 1420, in wrapper
    return func(self, *args, **kwargs)
  File "C:\Users\User\PycharmProjects\YouTube-\venv\lib\site-packages\yt_dlp\YoutubeDL.py", line 1490, in __extract_info
    ie_result = ie.extract(url)
  File "C:\Users\User\PycharmProjects\YouTube-\venv\lib\site-packages\yt_dlp\extractor\common.py", line 666, in extract
    raise type(e)(e.orig_msg, **kwargs)
yt_dlp.utils.ExtractorError: [youtube] FvnQJZnnXXo: Private video. Sign in if you've been granted access to this video

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\User\PycharmProjects\YouTube-\YouMain.py", line 105, in <module>
    run()
  File "C:\Users\User\PycharmProjects\YouTube-\YouMain.py", line 23, in run
    video_info = yb.YoutubeDL().extract_info(
  File "C:\Users\User\PycharmProjects\YouTube-\venv\lib\site-packages\yt_dlp\YoutubeDL.py", line 1411, in extract_info
    return self.__extract_info(url, self.get_info_extractor(ie_key), download, extra_info, process)
  File "C:\Users\User\PycharmProjects\YouTube-\venv\lib\site-packages\yt_dlp\YoutubeDL.py", line 1438, in wrapper
    self.report_error(str(e), e.format_traceback())
  File "C:\Users\User\PycharmProjects\YouTube-\venv\lib\site-packages\yt_dlp\YoutubeDL.py", line 962, in report_error
    self.trouble(f'{self._format_err("ERROR:", self.Styles.ERROR)} {message}', *args, **kwargs)
  File "C:\Users\User\PycharmProjects\YouTube-\venv\lib\site-packages\yt_dlp\YoutubeDL.py", line 905, in trouble
    raise DownloadError(message, exc_info)
yt_dlp.utils.DownloadError: ERROR: [youtube] FvnQJZnnXXo: Private video. Sign in if you've been granted access to this video


Solution

  • I have fixed the problem. The solution was to change a part of the code, the change is in the def run part from

    def run():
        while True:
            video_url = input("\nplease enter youtube video url: ")
            video_info = yb.YoutubeDL().extract_info(
                url=video_url, download=False)
            filename = f"{video_info['title']}"
    
            ydl_opts = {
                'format': 'bestvideo[ext=mp4]+bestaudio[ext=m4a]/bestvideo+bestaudio/best',
                'download_archive': 'downloaded_songs.txt',
                'windowsfilenames': True,
                'outtmpl': data + '/%(title)s.%(ext)s',
                'writesubtitles': True,
                'subtitleslangs': ['en', '-live_chat'],
                'writethumbnail': True,
                'embedthumbnail': True,
                'abort_on_unavailable_fragments': False,
                'ignoreerrors': True,
                'verbose': True,
                'postprocessors': [
                    {'key': 'FFmpegMetadata',
                     'add_metadata': True, },
                    {'key': 'FFmpegEmbedSubtitle'},
                    {'key': 'EmbedThumbnail',
                     'already_have_thumbnail': True,
                     },
                ]
            }
    
            with yb.YoutubeDL(ydl_opts) as ydl:
                ydl.download([video_info['webpage_url']])
                print("\nDownload complete... {}".format(filename))
                thumbnail_path()
                clear()
    

    to

    def run():
        while True:
            video_url = input("\nplease enter youtube video url: ")
            ydl_opts = {
                'format': 'bestvideo[ext=mp4]+bestaudio[ext=m4a]/bestvideo+bestaudio/best',
                'download_archive': 'downloaded_songs.txt',
                'windowsfilenames': True,
                'outtmpl': data + '/%(title)s.%(ext)s',
                'writesubtitles': True,
                'subtitleslangs': ['en', '-live_chat'],
                'writethumbnail': True,
                'embedthumbnail': True,
                'ignoreerrors': True,
                'postprocessors': [
                    {'key': 'FFmpegMetadata',
                     'add_metadata': True, },
                    {'key': 'FFmpegEmbedSubtitle'},
                    {'key': 'EmbedThumbnail',
                     'already_have_thumbnail': True,
                     },
                ],
            }
    
            with yt_dlp.YoutubeDL(ydl_opts) as ydl:
                error_code = ydl.download([video_url])
                video_info = ydl.extract_info(url=video_url, download=False)
                filename = f"{video_info['title']}"
                print('Some videos failed to download {}'.format(filename) if error_code
                      else "\nDownload complete... {}".format(filename))
                thumbnail_path()
                clear()
    

    the problem come from

    video_info = yb.YoutubeDL().extract_info(url=video_url, download=False)
    

    It would try to get the video info