Проблема с сертификацией SSL при использовании pytube

Есть код конвертера:

import re
import pytube

youtube_url_pattern = re.compile(r'https://www\.youtube\.com/watch\?v=[a-zA-Z0-9_-]+')

class Converter:
    """
    This module for converting Youtube videos to mp3 (or mp4 in this case)
    """
    def __init__(self, url):
        self.video = pytube.YouTube(url)
        self.name = self.video.title # имя видео
        self.thumbnail = self.video.thumbnail_url # превью видео
        self.stream = '140' # звуковая дорожка
        self.path = 'test/path' # тестовый репозиторий для видео

    def download(self):
        """Downloading files from Youtube"""
        print(f"Downloading {self.name}...")
        try:
            stream =  self.video.streams.get_by_itag(self.stream)
            return stream.download(output_path=self.path)
        except:
            return "Download was not succsesful, try again later"

    def show_image(self):
        """Returns images (use it on your website)"""
        return self.thumbnail

    @staticmethod
    def finish():
        """Just reminder that your covertion finished"""
        print("Finished!")

    def rename(self, new_name):
        self.name = new_name

if __name__ == '__main__':
    test_video = Converter('https://www.youtube.com/watch?v=4Mw0QJ5Udlw')
    test_video.download()

Раньше при запуске кода он жаловался на ssl сертификат, было что-то вроде ошибки:

urllib.error.URLError: <urlopen error [SSL: UNEXPECTED_EOF_WHILE_READING] EOF occurred in violation of protocol (_ssl.c:1006)>

точно сказать не могу как выглядела, поскольку после гугления были попытки решить:

  • pip install certifi (не помогло, но ошибка поменялась на urllib.error.URLError: <urlopen error [WinError 10054] Удаленный хост принудительно разорвал существующее подключение>
  • обновление библиотек не помогло

При запуске в терминале команды pytube https://www.youtube.com/watch?v=2lAe1cqCOXo выдаёт:

Loading video...
Traceback (most recent call last):
  File "d:\Python\Lib\urllib\request.py", line 1348, in do_open
    h.request(req.get_method(), req.selector, req.data, headers,
  File "d:\Python\Lib\http\client.py", line 1286, in request
    self._send_request(method, url, body, headers, encode_chunked)
  File "d:\Python\Lib\http\client.py", line 1332, in _send_request
    self.endheaders(body, encode_chunked=encode_chunked)
  File "d:\Python\Lib\http\client.py", line 1281, in endheaders
    self._send_output(message_body, encode_chunked=encode_chunked)
  File "d:\Python\Lib\http\client.py", line 1041, in _send_output
    self.send(msg)
  File "d:\Python\Lib\http\client.py", line 979, in send
    self.connect()
  File "d:\Python\Lib\http\client.py", line 1458, in connect
    self.sock = self._context.wrap_socket(self.sock,
                ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "d:\Python\Lib\ssl.py", line 517, in wrap_socket
    return self.sslsocket_class._create(
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "d:\Python\Lib\ssl.py", line 1108, in _create
    self.do_handshake()
  File "d:\Python\Lib\ssl.py", line 1379, in do_handshake
    self._sslobj.do_handshake()
ssl.SSLEOFError: [SSL: UNEXPECTED_EOF_WHILE_READING] EOF occurred in violation of protocol (_ssl.c:1006)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<frozen runpy>", line 198, in _run_module_as_main
  File "<frozen runpy>", line 88, in _run_code
  File "d:\Python\Scripts\pytube.exe\__main__.py", line 7, in <module>
  File "d:\Python\Lib\site-packages\pytube\cli.py", line 53, in main
    _perform_args_on_youtube(youtube, args)
  File "d:\Python\Lib\site-packages\pytube\cli.py", line 60, in _perform_args_on_youtube
    download_highest_resolution_progressive(
  File "d:\Python\Lib\site-packages\pytube\cli.py", line 474, in download_highest_resolution_progressive
    stream = youtube.streams.get_highest_resolution()
             ^^^^^^^^^^^^^^^
  File "d:\Python\Lib\site-packages\pytube\__main__.py", line 295, in streams
    self.check_availability()
  File "d:\Python\Lib\site-packages\pytube\__main__.py", line 210, in check_availability
    status, messages = extract.playability_status(self.watch_html)
                                                  ^^^^^^^^^^^^^^^
  File "d:\Python\Lib\site-packages\pytube\__main__.py", line 102, in watch_html
    self._watch_html = request.get(url=self.watch_url)
                       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "d:\Python\Lib\site-packages\pytube\request.py", line 53, in get
    response = _execute_request(url, headers=extra_headers, timeout=timeout)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "d:\Python\Lib\site-packages\pytube\request.py", line 37, in _execute_request
    return urlopen(request, timeout=timeout)  # nosec
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "d:\Python\Lib\urllib\request.py", line 216, in urlopen
    return opener.open(url, data, timeout)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "d:\Python\Lib\urllib\request.py", line 519, in open
    response = self._open(req, data)
               ^^^^^^^^^^^^^^^^^^^^^
  File "d:\Python\Lib\urllib\request.py", line 536, in _open
    result = self._call_chain(self.handle_open, protocol, protocol +
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "d:\Python\Lib\urllib\request.py", line 496, in _call_chain
    result = func(*args)
             ^^^^^^^^^^^
  File "d:\Python\Lib\urllib\request.py", line 1391, in https_open
    return self.do_open(http.client.HTTPSConnection, req,
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "d:\Python\Lib\urllib\request.py", line 1351, in do_open
    raise URLError(err)
urllib.error.URLError: <urlopen error [SSL: UNEXPECTED_EOF_WHILE_READING] EOF occurred in violation of protocol (_ssl.c:1006)>

Может можно как-нибудь отключить проверку ssl сертификатов?

  • OS: win 10
  • pytube: 15.0.0
  • certifi: 2024.2.2

Ответы (0 шт):