I wrote a script to find spelling mistakes in SO questions’ titles.
I used it for about a month.This was working fine.

But now, when I try to run it, I am getting this.

Traceback (most recent call last):
  File "copyeditor.py", line 32, in <module>
    find_bad_qn(i)
  File "copyeditor.py", line 15, in find_bad_qn
    html = urlopen(url)
  File "/usr/lib/python3.4/urllib/request.py", line 161, in urlopen
    return opener.open(url, data, timeout)
  File "/usr/lib/python3.4/urllib/request.py", line 469, in open
    response = meth(req, response)
  File "/usr/lib/python3.4/urllib/request.py", line 579, in http_response
    'http', request, response, code, msg, hdrs)
  File "/usr/lib/python3.4/urllib/request.py", line 507, in error
    return self._call_chain(*args)
  File "/usr/lib/python3.4/urllib/request.py", line 441, in _call_chain
    result = func(*args)
  File "/usr/lib/python3.4/urllib/request.py", line 587, in http_error_default
    raise HTTPError(req.full_url, code, msg, hdrs, fp)
urllib.error.HTTPError: HTTP Error 404: Not Found

This is my code

import json
from urllib.request import urlopen
from bs4 import BeautifulSoup
from enchant import DictWithPWL
from enchant.checker import SpellChecker

my_dict = DictWithPWL("en_US", pwl="terms.dict")
chkr = SpellChecker(lang=my_dict)
result = []


def find_bad_qn(a):
    url = "https://stackoverflow.com/questions?page=" + str(a) + "&sort=active"
    html = urlopen(url)
    bsObj = BeautifulSoup(html, "html5lib")
    que = bsObj.find_all("div", class_="question-summary")
    for div in que:
        link = div.a.get('href')
        name = div.a.text
        chkr.set_text(name.lower())
        list1 = []
        for err in chkr:
            list1.append(chkr.word)
        if (len(list1) > 1):
            str1 = ' '.join(list1)
            result.append({'link': link, 'name': name, 'words': str1})


print("Please Wait.. it will take some time")
for i in range(298314,298346):
    find_bad_qn(i)
for qn in result:
    qn['link'] = "https://stackoverflow.com" + qn['link']
for qn in result:
    print(qn['link'], " Error Words:", qn['words'])
    url = qn['link']

UPDATE

This is the url causing the problem.Even though this url exists.

https://stackoverflow.com/questions?page=298314&sort=active

I tried changing the range to some lower values. It works fine now.

Why this happened with above url?

I wrote a script to find spelling mistakes in SO questions’ titles.
I used it for about a month.This was working fine.

But now, when I try to run it, I am getting this.

Traceback (most recent call last):
  File "copyeditor.py", line 32, in <module>
    find_bad_qn(i)
  File "copyeditor.py", line 15, in find_bad_qn
    html = urlopen(url)
  File "/usr/lib/python3.4/urllib/request.py", line 161, in urlopen
    return opener.open(url, data, timeout)
  File "/usr/lib/python3.4/urllib/request.py", line 469, in open
    response = meth(req, response)
  File "/usr/lib/python3.4/urllib/request.py", line 579, in http_response
    'http', request, response, code, msg, hdrs)
  File "/usr/lib/python3.4/urllib/request.py", line 507, in error
    return self._call_chain(*args)
  File "/usr/lib/python3.4/urllib/request.py", line 441, in _call_chain
    result = func(*args)
  File "/usr/lib/python3.4/urllib/request.py", line 587, in http_error_default
    raise HTTPError(req.full_url, code, msg, hdrs, fp)
urllib.error.HTTPError: HTTP Error 404: Not Found

This is my code

import json
from urllib.request import urlopen
from bs4 import BeautifulSoup
from enchant import DictWithPWL
from enchant.checker import SpellChecker

my_dict = DictWithPWL("en_US", pwl="terms.dict")
chkr = SpellChecker(lang=my_dict)
result = []


def find_bad_qn(a):
    url = "https://stackoverflow.com/questions?page=" + str(a) + "&sort=active"
    html = urlopen(url)
    bsObj = BeautifulSoup(html, "html5lib")
    que = bsObj.find_all("div", class_="question-summary")
    for div in que:
        link = div.a.get('href')
        name = div.a.text
        chkr.set_text(name.lower())
        list1 = []
        for err in chkr:
            list1.append(chkr.word)
        if (len(list1) > 1):
            str1 = ' '.join(list1)
            result.append({'link': link, 'name': name, 'words': str1})


print("Please Wait.. it will take some time")
for i in range(298314,298346):
    find_bad_qn(i)
for qn in result:
    qn['link'] = "https://stackoverflow.com" + qn['link']
for qn in result:
    print(qn['link'], " Error Words:", qn['words'])
    url = qn['link']

UPDATE

This is the url causing the problem.Even though this url exists.

https://stackoverflow.com/questions?page=298314&sort=active

I tried changing the range to some lower values. It works fine now.

Why this happened with above url?

@FlubOtic

I’ve been getting this error ever since I downloaded pytube, which was only two weeks ago, but it keeps getting worse. At least 1 in 30 downloads will give me the error “urllib.error.HTTPError: HTTP Error 404: Not Found”

When I run the loop using the same YouTube link and Download location:

import pytube

for i in range(50):
    out_file = pytube.YouTube("https://www.youtube.com/watch?v=yHwGIA4VeOc").streams.first().download("D:\Music")
    print("Done")

I get the error “urllib.error.HTTPError: HTTP Error 404: Not Found” at least once during the loop.
Sometimes it will give the error on the 5th download, sometimes on the 43rd. It is random. If I’m lucky it will download them all successfully, but that almost never happens.

I’ve tried putting a delay between downloads and looping through a list of links instead of using the same link for each download, but neither worked.

There is an old issue from 2019, where people have left comments having the same issue within the last two weeks, so I’m not the only one.

Information:

  • Python 3.9.5
  • Pytube 10.8.1
  • I used “python -m pip install git+https://github.com/pytube/pytube” to download pytube

@github-actions

Thank you for contributing to PyTube. Please remember to reference Contributing.md

@xnetcat

@Loki-Hornsby

Can confirm too –
can also happen when using PyQt5 Threads. Delaying the command from being run inside the thread also results in what OP says too.

@tfdahlin

@FlubOtic and @Bobbymcbobface can you each provide the full error traceback so that I can see where in the code this is failing? I’m wondering if this is only happening when vid_info_raw is fetched, or if other processes are also causing the problem.

@rolisanchez

Can confirm too.

Full traceback:

Traceback (most recent call last):
  File "/Users/victorrolandosanchezjara/Programming/youtube-downloader-python/download.py", line 8, in <module>
    print('Downloading video - ', current_video, ' :', yt.title)
  File "/usr/local/anaconda3/lib/python3.7/site-packages/pytube/__main__.py", line 351, in title
    self._title = self.player_response['videoDetails']['title']
  File "/usr/local/anaconda3/lib/python3.7/site-packages/pytube/__main__.py", line 167, in player_response
    if isinstance(self.player_config_args["player_response"], str):
  File "/usr/local/anaconda3/lib/python3.7/site-packages/pytube/__main__.py", line 187, in player_config_args
    self._player_config_args = self.vid_info
  File "/usr/local/anaconda3/lib/python3.7/site-packages/pytube/__main__.py", line 278, in vid_info
    return dict(parse_qsl(self.vid_info_raw))
  File "/usr/local/anaconda3/lib/python3.7/site-packages/pytube/__main__.py", line 108, in vid_info_raw
    self._vid_info_raw = request.get(self.vid_info_url)
  File "/usr/local/anaconda3/lib/python3.7/site-packages/pytube/request.py", line 52, in get
    response = _execute_request(url, headers=extra_headers, timeout=timeout)
  File "/usr/local/anaconda3/lib/python3.7/site-packages/pytube/request.py", line 36, in _execute_request
    return urlopen(request, timeout=timeout)  # nosec
  File "/usr/local/anaconda3/lib/python3.7/urllib/request.py", line 222, in urlopen
    return opener.open(url, data, timeout)
  File "/usr/local/anaconda3/lib/python3.7/urllib/request.py", line 531, in open
    response = meth(req, response)
  File "/usr/local/anaconda3/lib/python3.7/urllib/request.py", line 641, in http_response
    'http', request, response, code, msg, hdrs)
  File "/usr/local/anaconda3/lib/python3.7/urllib/request.py", line 563, in error
    result = self._call_chain(*args)
  File "/usr/local/anaconda3/lib/python3.7/urllib/request.py", line 503, in _call_chain
    result = func(*args)
  File "/usr/local/anaconda3/lib/python3.7/urllib/request.py", line 755, in http_error_302
    return self.parent.open(new, timeout=req.timeout)
  File "/usr/local/anaconda3/lib/python3.7/urllib/request.py", line 531, in open
    response = meth(req, response)
  File "/usr/local/anaconda3/lib/python3.7/urllib/request.py", line 641, in http_response
    'http', request, response, code, msg, hdrs)
  File "/usr/local/anaconda3/lib/python3.7/urllib/request.py", line 569, in error
    return self._call_chain(*args)
  File "/usr/local/anaconda3/lib/python3.7/urllib/request.py", line 503, in _call_chain
    result = func(*args)
  File "/usr/local/anaconda3/lib/python3.7/urllib/request.py", line 649, in http_error_default
    raise HTTPError(req.full_url, code, msg, hdrs, fp)
urllib.error.HTTPError: HTTP Error 404: Not Found

My code is quite simple. Downloading a list of videos.

from tqdm import tqdm
from pytube import YouTube

with open('videos_list.txt') as videos_list:
    current_video = 1
    for url in tqdm(videos_list, desc='Downloading videos'):
        yt = YouTube(url)
        print('Downloading video - ', current_video, ' :', yt.title)
        yt.streams.first().download('./videos/'+yt.title)
        print('Finished downloading video - ', current_video, ' :', yt.title)
        current_video += 1

@FlubOtic

@tfdahlin here is my full traceback:

Traceback (most recent call last):
  File "c:\Users\znmca\VSCode\Spotify-Playlist-Downloader\pytubes.py", line 4, in <module>
    out_file = pytube.YouTube("https://www.youtube.com/watch?v=yHwGIA4VeOc").streams.first().download("D:\Music")
  File "C:\Users\znmca\AppData\Local\Programs\Python\Python39\lib\site-packages\pytube\__main__.py", line 308, in streams
    return StreamQuery(self.fmt_streams)
  File "C:\Users\znmca\AppData\Local\Programs\Python\Python39\lib\site-packages\pytube\__main__.py", line 213, in fmt_streams
    if "adaptive_fmts" in self.player_config_args:
  File "C:\Users\znmca\AppData\Local\Programs\Python\Python39\lib\site-packages\pytube\__main__.py", line 187, in player_config_args
    self._player_config_args = self.vid_info
  File "C:\Users\znmca\AppData\Local\Programs\Python\Python39\lib\site-packages\pytube\__main__.py", line 278, in vid_info
    return dict(parse_qsl(self.vid_info_raw))
  File "C:\Users\znmca\AppData\Local\Programs\Python\Python39\lib\site-packages\pytube\__main__.py", line 108, in vid_info_raw
    self._vid_info_raw = request.get(self.vid_info_url)
  File "C:\Users\znmca\AppData\Local\Programs\Python\Python39\lib\site-packages\pytube\request.py", line 52, in get
    response = _execute_request(url, headers=extra_headers, timeout=timeout)
  File "C:\Users\znmca\AppData\Local\Programs\Python\Python39\lib\site-packages\pytube\request.py", line 36, in _execute_request
    return urlopen(request, timeout=timeout)  # nosec
  File "C:\Users\znmca\AppData\Local\Programs\Python\Python39\lib\urllib\request.py", line 214, in urlopen
    return opener.open(url, data, timeout)
  File "C:\Users\znmca\AppData\Local\Programs\Python\Python39\lib\urllib\request.py", line 523, in open
    response = meth(req, response)
  File "C:\Users\znmca\AppData\Local\Programs\Python\Python39\lib\urllib\request.py", line 632, in http_response
    response = self.parent.error(
  File "C:\Users\znmca\AppData\Local\Programs\Python\Python39\lib\urllib\request.py", line 555, in error
    result = self._call_chain(*args)
  File "C:\Users\znmca\AppData\Local\Programs\Python\Python39\lib\urllib\request.py", line 494, in _call_chain
    result = func(*args)
  File "C:\Users\znmca\AppData\Local\Programs\Python\Python39\lib\urllib\request.py", line 747, in http_error_302
    return self.parent.open(new, timeout=req.timeout)
  File "C:\Users\znmca\AppData\Local\Programs\Python\Python39\lib\urllib\request.py", line 523, in open
    response = meth(req, response)
  File "C:\Users\znmca\AppData\Local\Programs\Python\Python39\lib\urllib\request.py", line 632, in http_response
    response = self.parent.error(
  File "C:\Users\znmca\AppData\Local\Programs\Python\Python39\lib\urllib\request.py", line 561, in error
    return self._call_chain(*args)
  File "C:\Users\znmca\AppData\Local\Programs\Python\Python39\lib\urllib\request.py", line 494, in _call_chain
    result = func(*args)
  File "C:\Users\znmca\AppData\Local\Programs\Python\Python39\lib\urllib\request.py", line 641, in http_error_default
    raise HTTPError(req.full_url, code, msg, hdrs, fp)
urllib.error.HTTPError: HTTP Error 404: Not Found

@Loki-Hornsby

Heres my Traceback too bud

Traceback (most recent call last):
 File "X:\Youtube Downloader\DownloadApp.pyw", line 54, in run
   result = self.fn(*self.args, **self.kwargs)
 File "X:\Youtube Downloader\DownloadApp.pyw", line 174, in Download
   vids = yt.streams.filter(only_audio=True).all()
 File "C:\Users\L\AppData\Local\Programs\Python\Python39\lib\site-packages\pytube\__main__.py", line 308, in streams
   return StreamQuery(self.fmt_streams)
 File "C:\Users\L\AppData\Local\Programs\Python\Python39\lib\site-packages\pytube\__main__.py", line 213, in fmt_streams
   if "adaptive_fmts" in self.player_config_args:
 File "C:\Users\L\AppData\Local\Programs\Python\Python39\lib\site-packages\pytube\__main__.py", line 187, in player_config_args
   self._player_config_args = self.vid_info
 File "C:\Users\L\AppData\Local\Programs\Python\Python39\lib\site-packages\pytube\__main__.py", line 278, in vid_info
   return dict(parse_qsl(self.vid_info_raw))
 File "C:\Users\L\AppData\Local\Programs\Python\Python39\lib\site-packages\pytube\__main__.py", line 108, in vid_info_raw
   self._vid_info_raw = request.get(self.vid_info_url)
 File "C:\Users\L\AppData\Local\Programs\Python\Python39\lib\site-packages\pytube\request.py", line 52, in get
   response = _execute_request(url, headers=extra_headers, timeout=timeout)
 File "C:\Users\L\AppData\Local\Programs\Python\Python39\lib\site-packages\pytube\request.py", line 36, in _execute_request
   return urlopen(request, timeout=timeout)  # nosec
 File "C:\Users\L\AppData\Local\Programs\Python\Python39\lib\urllib\request.py", line 214, in urlopen
   return opener.open(url, data, timeout)
 File "C:\Users\L\AppData\Local\Programs\Python\Python39\lib\urllib\request.py", line 523, in open
   response = meth(req, response)
 File "C:\Users\L\AppData\Local\Programs\Python\Python39\lib\urllib\request.py", line 632, in http_response
   response = self.parent.error(
 File "C:\Users\L\AppData\Local\Programs\Python\Python39\lib\urllib\request.py", line 555, in error
   result = self._call_chain(*args)
 File "C:\Users\L\AppData\Local\Programs\Python\Python39\lib\urllib\request.py", line 494, in _call_chain
   result = func(*args)
 File "C:\Users\L\AppData\Local\Programs\Python\Python39\lib\urllib\request.py", line 747, in http_error_302
   return self.parent.open(new, timeout=req.timeout)
 File "C:\Users\L\AppData\Local\Programs\Python\Python39\lib\urllib\request.py", line 523, in open
   response = meth(req, response)
 File "C:\Users\L\AppData\Local\Programs\Python\Python39\lib\urllib\request.py", line 632, in http_response
   response = self.parent.error(
 File "C:\Users\L\AppData\Local\Programs\Python\Python39\lib\urllib\request.py", line 561, in error
   return self._call_chain(*args)
 File "C:\Users\L\AppData\Local\Programs\Python\Python39\lib\urllib\request.py", line 494, in _call_chain
   result = func(*args)
 File "C:\Users\L\AppData\Local\Programs\Python\Python39\lib\urllib\request.py", line 641, in http_error_default
   raise HTTPError(req.full_url, code, msg, hdrs, fp)
urllib.error.HTTPError: HTTP Error 404: Not Found

@tfdahlin

ty for all the tracebacks, it looks like it is an issue with just the vid info url, I’ll see if I can investigate what’s causing it sometime this week

@cottuli

@tfdahlin I’ve been getting the same error using the CLI (so I’m not looping through multiple urls at once like @FlubOtic), but the error still seems to occur randomly, and I’ve found that if I try to download the same video a few times in a row the download will eventually succeed (after failing with the above error on the first couple of tries).

@tfdahlin

I might just do a slight refactor to make certain web requests have an auto-retry policy to see if that fixes the issue

@develarts

Hello, i have the same error and i thought it is my bad. I have created a sentry implement to see the error better.
Here is a screenshot what they do.
For the first i think my post url is wrong, so pytube dont get any url but they do.
Sometime it work and sometime not. like 50/50
For me i looks like grabing the link – works – grabbing video info – works and then try to catch video info again and failed. i dont know why pytube is trying to grab it again.
Opera Momentaufnahme_2021-05-19_201901_sentry io

@Nosh-Ware

I’ve had this same issue to. Nothing else realy to add other then my hopes of this being fixed. It feels almost random when I get this error, and thats not even form itterating a list or dowlaoding a playlist. Thats just trying a single link.

@mcoirad-gmmb

Just wanted to add that I think auto-retry policy would be a good idea, I was running into the 404 issue as well and solved, or at least got things working again, by retrying X number of times.

@Earph0nes

Getting this 100% of the time now. Code functioned yesterday with the exception of getting this error once or twice.

@FlubOtic

@tfdahlin The download function no longer works for me. Getting the error on every download now just like @Earph0nes. I don’t think an auto-retry will fix it anymore.

@Nosh-Ware

To be fair, it seems to fair up when done in sucession. That being said there is stll a random chance regardless of it working. Maybe its youtube trying to put a damper on this type of acess?

@FlubOtic

@Nosh-Ware That is what I thought also, but when you go to sites like this you get no errors. So it most likely is a pytube bug, not YouTube preventing it. Also, can you run your code and see if the download function works for you anymore. It stopped working completely for me and another user just a moment ago.

@tfdahlin

Hello, i have the same error and i thought it is my bad. I have created a sentry implement to see the error better.
Here is a screenshot what they do.
For the first i think my post url is wrong, so pytube dont get any url but they do.
Sometime it work and sometime not. like 50/50
For me i looks like grabing the link – works – grabbing video info – works and then try to catch video info again and failed. i dont know why pytube is trying to grab it again.
Opera Momentaufnahme_2021-05-19_201901_sentry io

The reason that it looks like it’s making a request twice is because of the 301 redirect. The library only makes the request once, but behind the scenes httplib is making a request to youtube.com/, getting redirected to www.youtube.com, and then proceeding with the request there.

@ the rest of y’all, I’m going to spend tonight seeing if I can get this fixed

FlubOtic, develarts, TiredBot, rem2, kavorite, xtinamarie, Earph0nes, and itaisir reacted with hooray emoji
FlubOtic, Sasiam, develarts, TiredBot, rem2, kavorite, xtinamarie, Earph0nes, zpatty, Kikumu, and 4 more reacted with heart emoji

@tfdahlin

Update: I think I found a way around using the get_video_info url, I’m working on updating supporting functions that relied on this information now.

FlubOtic, Cynose, 1shershah, Sasiam, zpatty, drwjf, tehface, Kikumu, kavorite, rem2, and 2 more reacted with heart emoji

@tfdahlin

Still in progress, have to sleep for now. Currently running into a 403 issue if anybody wants to check out my branch to try and solve it. Otherwise I’ll try resume work on this tomorrow afternoon

@Ssuwani

Problem is get_video_info , change code in pytube/extract.py

def _video_info_url(params: OrderedDict) -> str:     
    return "https://www.youtube.com/get_video_info?html5=1&amp;video_id=" + params['video_id']

not

def _video_info_url(params: OrderedDict) -> str:    
    return "https://youtube.com/get_video_info?" + urlencode(params) 

PR/996

supermomie, kavorite, Adriano13S, iridium87, ajshuler, JackScott7, and hongsamvo reacted with thumbs up emoji
supermomie, kavorite, and bigbear22941 reacted with hooray emoji
supermomie, jcarosi, Ssuwani, and kavorite reacted with heart emoji

@supermomie

@bigbear22941

works not for me, get error ‘player respone’ 🙁

@teoaltinoz

Not working, I’m also getting the “KeyError: ‘player_response'” error

EDIT:
I fixed it by removing [‘player_response’] on line 190 in __main__.py
So it should look something like this:
if 'streamingData' not in self.player_config_args:
But I don’t know if this is a proper fix.

domaslasauskas, ab-anand, bigbear22941, Adriano13S, DontDieDIY, 15minutOdmora, ajshuler, lisbonjoker, and JackScott7 reacted with thumbs up emoji
ab-anand, bigbear22941, and 15minutOdmora reacted with hooray emoji

@kpitan022

Not working. My traceback

  File "/data/user/0/ru.iiec.pydroid3/files/accomp_files/iiec_run/iiec_run.py", line 31, in <module>
    start(fakepyfile,mainpyfile)
  File "/data/user/0/ru.iiec.pydroid3/files/accomp_files/iiec_run/iiec_run.py", line 30, in start
    exec(open(mainpyfile).read(),  __main__.__dict__)
  File "<string>", line 3, in <module>
  File "/data/user/0/ru.iiec.pydroid3/files/aarch64-linux-android/lib/python3.8/site-packages/pytube/__main__.py", line 317, in thumbnail_url
    self.player_response.get("videoDetails", {})
  File "/data/user/0/ru.iiec.pydroid3/files/aarch64-linux-android/lib/python3.8/site-packages/pytube/__main__.py", line 167, in player_response
    if isinstance(self.player_config_args["player_response"], str):
  File "/data/user/0/ru.iiec.pydroid3/files/aarch64-linux-android/lib/python3.8/site-packages/pytube/__main__.py", line 187, in player_config_args
    self._player_config_args = self.vid_info
  File "/data/user/0/ru.iiec.pydroid3/files/aarch64-linux-android/lib/python3.8/site-packages/pytube/__main__.py", line 278, in vid_info
    return dict(parse_qsl(self.vid_info_raw))
  File "/data/user/0/ru.iiec.pydroid3/files/aarch64-linux-android/lib/python3.8/site-packages/pytube/__main__.py", line 108, in vid_info_raw
    self._vid_info_raw = request.get(self.vid_info_url)
  File "/data/user/0/ru.iiec.pydroid3/files/aarch64-linux-android/lib/python3.8/site-packages/pytube/request.py", line 53, in get
    response = _execute_request(url, headers=extra_headers, timeout=timeout)
  File "/data/user/0/ru.iiec.pydroid3/files/aarch64-linux-android/lib/python3.8/site-packages/pytube/request.py", line 37, in _execute_request
    return urlopen(request, timeout=timeout)  # nosec
  File "/data/user/0/ru.iiec.pydroid3/files/aarch64-linux-android/lib/python3.8/urllib/request.py", line 222, in urlopen
    return opener.open(url, data, timeout)
  File "/data/user/0/ru.iiec.pydroid3/files/aarch64-linux-android/lib/python3.8/urllib/request.py", line 531, in open
    response = meth(req, response)
  File "/data/user/0/ru.iiec.pydroid3/files/aarch64-linux-android/lib/python3.8/urllib/request.py", line 640, in http_response
    response = self.parent.error(
  File "/data/user/0/ru.iiec.pydroid3/files/aarch64-linux-android/lib/python3.8/urllib/request.py", line 563, in error
    result = self._call_chain(*args)
  File "/data/user/0/ru.iiec.pydroid3/files/aarch64-linux-android/lib/python3.8/urllib/request.py", line 502, in _call_chain
    result = func(*args)
  File "/data/user/0/ru.iiec.pydroid3/files/aarch64-linux-android/lib/python3.8/urllib/request.py", line 755, in http_error_302
    return self.parent.open(new, timeout=req.timeout)
  File "/data/user/0/ru.iiec.pydroid3/files/aarch64-linux-android/lib/python3.8/urllib/request.py", line 531, in open
    response = meth(req, response)
  File "/data/user/0/ru.iiec.pydroid3/files/aarch64-linux-android/lib/python3.8/urllib/request.py", line 640, in http_response
    response = self.parent.error(
  File "/data/user/0/ru.iiec.pydroid3/files/aarch64-linux-android/lib/python3.8/urllib/request.py", line 569, in error
    return self._call_chain(*args)
  File "/data/user/0/ru.iiec.pydroid3/files/aarch64-linux-android/lib/python3.8/urllib/request.py", line 502, in _call_chain
    result = func(*args)
  File "/data/user/0/ru.iiec.pydroid3/files/aarch64-linux-android/lib/python3.8/urllib/request.py", line 649, in http_error_default
    raise HTTPError(req.full_url, code, msg, hdrs, fp)
urllib.error.HTTPError: HTTP Error 404: Not Found

[Program finished]```

@Mauratay

Same issue with all downloads.

  File "test.py", line 4, in <module>
    YouTube('https://youtu.be/9bZkp7q19f0').streams.first().download()
  File "/home/pancho/.local/lib/python3.8/site-packages/pytube/__main__.py", line 309, in streams
    return StreamQuery(self.fmt_streams)
  File "/home/pancho/.local/lib/python3.8/site-packages/pytube/__main__.py", line 214, in fmt_streams
    if "adaptive_fmts" in self.player_config_args:
  File "/home/pancho/.local/lib/python3.8/site-packages/pytube/__main__.py", line 188, in player_config_args
    self._player_config_args = self.vid_info
  File "/home/pancho/.local/lib/python3.8/site-packages/pytube/__main__.py", line 279, in vid_info
    return dict(parse_qsl(self.vid_info_raw))
  File "/home/pancho/.local/lib/python3.8/site-packages/pytube/__main__.py", line 109, in vid_info_raw
    self._vid_info_raw = request.get(self.vid_info_url)
  File "/home/pancho/.local/lib/python3.8/site-packages/pytube/request.py", line 54, in get
    response = _execute_request(url, headers=extra_headers, timeout=timeout)
  File "/home/pancho/.local/lib/python3.8/site-packages/pytube/request.py", line 38, in _execute_request
    return urlopen(request, timeout=timeout)  # nosec
  File "/usr/lib/python3.8/urllib/request.py", line 222, in urlopen
    return opener.open(url, data, timeout)
  File "/usr/lib/python3.8/urllib/request.py", line 531, in open
    response = meth(req, response)
  File "/usr/lib/python3.8/urllib/request.py", line 640, in http_response
    response = self.parent.error(
  File "/usr/lib/python3.8/urllib/request.py", line 563, in error
    result = self._call_chain(*args)
  File "/usr/lib/python3.8/urllib/request.py", line 502, in _call_chain
    result = func(*args)
  File "/usr/lib/python3.8/urllib/request.py", line 755, in http_error_302
    return self.parent.open(new, timeout=req.timeout)
  File "/usr/lib/python3.8/urllib/request.py", line 531, in open
    response = meth(req, response)
  File "/usr/lib/python3.8/urllib/request.py", line 640, in http_response
    response = self.parent.error(
  File "/usr/lib/python3.8/urllib/request.py", line 569, in error
    return self._call_chain(*args)
  File "/usr/lib/python3.8/urllib/request.py", line 502, in _call_chain
    result = func(*args)
  File "/usr/lib/python3.8/urllib/request.py", line 649, in http_error_default
    raise HTTPError(req.full_url, code, msg, hdrs, fp)
urllib.error.HTTPError: HTTP Error 404: Not Found 

MCVE:

from pytube import YouTube, Playlist

anslist= """
1) music genre here
2) music genre here
3) music genre here
4) music genre here 
5) music genre here
6) music genre here
7) music genre here
8) music genre here
"""

def location(ans):
    destination=""
    if ans == 1:
        destination = "/destination"
        return destination
    elif ans == 2:
        destination = "/destination"
        return destination
    elif ans == 3:
        destination = "/destination"
        return destination
    elif ans == 4:
        destination = "/destination"
        return destination
    elif ans == 5:
        destination = "/destination"
        return destination
    elif ans == 6:
        destination = "/destination"
        return destination
    elif ans == 7:
        destination = "/destination"
        return destination
    elif ans == 8:
        destination = "/destination"
        return destination
   

def individual(url):
    print(anslist)
    dire = int(input("Set download destination: "))
    destination=location(dire)
    YouTube(f'{url}').streams.filter(only_audio=True).first()
    yt = YouTube(f'{url}')
    down = yt.streams.filter(only_audio=True).first()
    print("Downloading: " + str(yt.title))
    out_file = down.download(output_path=destination)
    base, ext = os.path.splitext(out_file)
    new_file = base + '.mp3'
    os.rename(out_file, new_file)



def playlist(pl):
    print(anslist)
    dire = int(input("Set download destination: "))
    destination=location(dire)
    p = Playlist(f'{pl}')
    for video in p.videos:
        down = video.streams.filter(only_audio=True).first()
        print("Downloading: " + str(video.title))
        out_file = down.download(output_path=destination)
        base, ext = os.path.splitext(out_file)
        new_file = base + '.mp3'
        os.rename(out_file, new_file)


def individualVideo(url):
    print(anslist)
    dire = int(input("Set download destination: "))
    destination=location(dire)
    YouTube(f'{url}').streams.first()
    yt = YouTube(f'{url}')
    down = yt.streams.filter(only_audio=True).first()
    out_file = down.download(output_path=destination)
    base, ext = os.path.splitext(out_file)
    print("Downloading: " + str(yt.title))



def playlistVideo(pl):
    print(anslist)
    dire = int(input("Set download destination: "))
    destination=location(dire)
    p = Playlist(f'{pl}')
    for video in p.videos:
        down = video.streams.first()
        out_file = down.download(output_path=destination)
        base, ext = os.path.splitext(out_file)
        print("Downloading: " + str(video.title))


def audio():
    ans = input("Single song or playlist? [s, p] ")
    if ans == "s":
        url = input("Paste URL: ")
        individual(url)
    else:
        url = input("Paste URL: ")
        playlist(url)


def video():
    ans = input("Single song or playlist? [s, p] ")
    if ans == "s":
        url = input("Paste URL: ")
        individualVideo(url)
    else:
        url = input("Paste URL: ")
        playlistVideo(url)

print(""" 
        _                                                 
      ,´ `.                                               
______|___|______________________________________________
      |  /                       _..-´|                  
      | /                  _..-´´_..-´|                  
______|/__________________|_..-´´_____|__________|\______
     ,|                   |           |          | \     
    / |                   |           |          | ´     
___/__|___________________|___________|__________|_______
  / ,´| `.                |      ,d88b|          |       
 | .  |   \            __ |      88888|       __ |       
_|_|__|____|_________,d88b|______`Y88P'_____,d88b|_______
 |  ` |    |         88888|                 88888|       
 `.   |   /          `Y88P'                 `Y88P'       
___`._|_.´_______________________________________________
      |                                                  
    , |                                  GP              
    '.´
Let's rock and roll!
____________________________
""")
ans=input("Audio or video? [a, v] ")
if ans == "a":
    audio()
else:
    video() 

@1shershah

Problem is get_video_info , change code in pytube/extract.py

def _video_info_url(params: OrderedDict) -> str:     
    return "https://www.youtube.com/get_video_info?html5=1&amp;video_id=" + params['video_id']

not

def _video_info_url(params: OrderedDict) -> str:    
    return "https://youtube.com/get_video_info?" + urlencode(params) 

PR/996

Solution works for me. I saw some responses with “player_response” being an error , just be sure you have this :
return “https://www.youtube.com/get_video_info?html5=1&video_id=” + params[‘video_id’]
Notice the lack of “amp;” , if you have that the reponse comes back as “status: fail” and hence no player_response in returned response

@DontDieDIY

Not working, I’m also getting the “KeyError: ‘player_response'” error

EDIT:
I fixed it by removing [‘player_response’] on line 190 in __main__.py
So it should look something like this:
if 'streamingData' not in self.player_config_args:
But I don’t know if this is a proper fix.

Ssuwani fix +This fixed it for me

@Cuti-Tox

link = input()
yt = YouTube(link) 
vid = yt.streams.get_highest_resolution()
vid.download("C:/Users/Home/Downloads", filename_prefix = "Video - ", max_retries = 13)
print("Done")```

It was working yesterday but not today, any fix? (Project submissions tomorrow pls)

@odkok

After I tried Ssuwani’s method, I got KeyError: ‘player_response’ as well, here’s my traceback

Traceback (most recent call last):
  File "fixed.py", line 7, in <module>
    print(yt.streams)
  File "C:\Users\wilson\anaconda3\envs\bugfix\lib\site-packages\pytube\__main__.py", line 308, in streams
    return StreamQuery(self.fmt_streams)
  File "C:\Users\wilson\anaconda3\envs\bugfix\lib\site-packages\pytube\__main__.py", line 213, in fmt_streams
    if "adaptive_fmts" in self.player_config_args:
  File "C:\Users\wilson\anaconda3\envs\bugfix\lib\site-packages\pytube\__main__.py", line 190, in player_config_args
    if 'streamingData' not in self.player_config_args['player_response']:
KeyError: 'player_response'

And 1shershah’s solution works for me 👍

Solution works for me. I saw some responses with “player_response” being an error , just be sure you have this :
return “https://www.youtube.com/get_video_info?html5=1&video_id=” + params[‘video_id’]
Notice the lack of “amp;” , if you have that the reponse comes back as “status: fail” and hence no player_response in returned response

@FlubOtic

Ssuwani’s fix gets rid of the 404 Error, but when I ran the download 100 times I got one 403 Error.

@drwjf

#998

Same logic as Ssuwani’s #996 . But keep old code convention and style.

@tfdahlin

Hey folks; I’m going to merge the PR @drwjf made once the CI tests pass. Expect v10.8.2 to be on pypi in the next 10 minutes or so.

@tfdahlin
tfdahlin

linked a pull request

May 20, 2021

that will
close
this issue

@tfdahlin

Before I merge #998, I am going to note here that I will likely still continue work on #994, just with a slightly lower priority since the additional parameter seems to fix the current issue.

@tfdahlin

python -m pip install --upgrade pytube should install the fix now. If there are further issues with v10.8.2, please open a new ticket so they get documented properly

@kpitan022

@tfdahlin

Huge thank you to @Ssuwani for the proposed solution, and @drwjf for adapting it to the existing code convention while I was unavailable

@DmitryCherneckiy

Good! Thanks for the quick response and solution to the problem.

@Suave101

@Pigi-bytes

Hello, i stil have the issue : pytube 10.8.3, in a Thread return error : HTTP Error 404: Not Found

In the debugger, metada and date are correct ; title or captions is equal to None.
image_2021-05-31_000514
( if you need to have the return in plan text i can do it )

Here my code ( full at https://github.com/Pigi-bytes/PigiTube )

def Thread_for_get_data(self):
    """
    Here, we watch if a url is valid, and if it is, we update the GUI, title and thumbnail
    """
    self.youtube_url = self.input.text()
    try:
        # If an error occurs here, that means that the url is not valide
        if len(self.youtube_url) != 43:
            self.error_in_thread_ok = True
            raise('Url pas de la bonne taille')

        self.video = pytube.YouTube(self.youtube_url)
        # We create the video objet, which contains the video we want
        # we use that object for all of the downloading process

        self.titre_yt = self.video.title

        ID = self.youtube_url[-11:]
        thumbnail_link = f"http://img.youtube.com/vi/{ID}/hqdefault.jpg"
        # We create the url of the thumbnail.
        # first of all we take the ID of the youtube video, the last 11 character.
        # We add that in a url and we can now have the link of the picture used for the thumbnail,
        # is a 480 x 360 px, jpg. => https://yt-thumb.canbeuseful.com/en
    except Exception as e: 
        print(e)
        self.error_in_thread_ok = True
        # if something went wrong with the url

Can someone explain to me what’s going on (I didn’t really understand, I admit)

@tfdahlin

@Pigi-bytes can you give me the video URL that you’re having the issue with please?

@SergeZ23

I get the same error on certain videos with pytube version 10.8.4

Traceback (most recent call last):
File "C:\Users\Serge\PycharmProjects\Youtube\venv\lib\site-packages\pytube\streams.py", line 261, in download
  max_retries=max_retries
File "C:\Users\Serge\PycharmProjects\Youtube\venv\lib\site-packages\pytube\request.py", line 160, in stream
  timeout=timeout
File "C:\Users\Serge\PycharmProjects\Youtube\venv\lib\site-packages\pytube\request.py", line 36, in _execute_request
  return urlopen(request, timeout=timeout)  # nosec
File "C:\Users\Serge\AppData\Local\Programs\Python\Python37-32\lib\urllib\request.py", line 222, in urlopen
  return opener.open(url, data, timeout)
File "C:\Users\Serge\AppData\Local\Programs\Python\Python37-32\lib\urllib\request.py", line 531, in open
  response = meth(req, response)
File "C:\Users\Serge\AppData\Local\Programs\Python\Python37-32\lib\urllib\request.py", line 641, in http_response
  'http', request, response, code, msg, hdrs)
File "C:\Users\Serge\AppData\Local\Programs\Python\Python37-32\lib\urllib\request.py", line 569, in error
  return self._call_chain(*args)
File "C:\Users\Serge\AppData\Local\Programs\Python\Python37-32\lib\urllib\request.py", line 503, in _call_chain
  result = func(*args)
File "C:\Users\Serge\AppData\Local\Programs\Python\Python37-32\lib\urllib\request.py", line 649, in http_error_default
  raise HTTPError(req.full_url, code, msg, hdrs, fp)
urllib.error.HTTPError: HTTP Error 404: Not Found

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "C:/Users/Serge/PycharmProjects/Youtube/Download.py", line 161, in <module>
  video_test('https://www.youtube.com/watch?v=dCqHdHKvSos')
File "C:/Users/Serge/PycharmProjects/Youtube/Download.py", line 154, in video_test
  video_download(video)
File "C:/Users/Serge/PycharmProjects/Youtube/Download.py", line 87, in video_download
  stream.download(output_path=complete_name, filename='VIDEO_' + title)
File "C:\Users\Serge\PycharmProjects\Youtube\venv\lib\site-packages\pytube\streams.py", line 274, in download
  max_retries=max_retries
File "C:\Users\Serge\PycharmProjects\Youtube\venv\lib\site-packages\pytube\request.py", line 127, in seq_stream
  yield from stream(url, timeout=timeout, max_retries=max_retries)
File "C:\Users\Serge\PycharmProjects\Youtube\venv\lib\site-packages\pytube\request.py", line 160, in stream
  timeout=timeout
File "C:\Users\Serge\PycharmProjects\Youtube\venv\lib\site-packages\pytube\request.py", line 36, in _execute_request
  return urlopen(request, timeout=timeout)  # nosec
File "C:\Users\Serge\AppData\Local\Programs\Python\Python37-32\lib\urllib\request.py", line 222, in urlopen
  return opener.open(url, data, timeout)
File "C:\Users\Serge\AppData\Local\Programs\Python\Python37-32\lib\urllib\request.py", line 531, in open
  response = meth(req, response)
File "C:\Users\Serge\AppData\Local\Programs\Python\Python37-32\lib\urllib\request.py", line 641, in http_response
  'http', request, response, code, msg, hdrs)
File "C:\Users\Serge\AppData\Local\Programs\Python\Python37-32\lib\urllib\request.py", line 569, in error
  return self._call_chain(*args)
File "C:\Users\Serge\AppData\Local\Programs\Python\Python37-32\lib\urllib\request.py", line 503, in _call_chain
  result = func(*args)
File "C:\Users\Serge\AppData\Local\Programs\Python\Python37-32\lib\urllib\request.py", line 649, in http_error_default
  raise HTTPError(req.full_url, code, msg, hdrs, fp)
urllib.error.HTTPError: HTTP Error 404: Not Found

I’m downloading streams that are not progressive, sometimes it would download the video stream and fail on the audio, sometimes it would fail on the video stream. I’ve also seen a case where on the first try I was able to download the video stream and failed on the audio, but on the second try with the same video, the error has occured while trying to download the video stream that has been downloaded successfully before that. The code is:

   stream = yt.streams.filter(file_extension='mp4', res='1080p').first()
    stream_audio = yt.streams.filter(file_extension='mp4', only_audio=True).order_by('abr').last()
    stream.download(output_path=complete_name, filename='VIDEO_' + title)
    stream_audio.download(output_path=complete_name, filename='AUDIO_' + title)

@billsioros

Can we please re-open this issue as it seems that it has not been fully resolved ? I’m facing the same problem as @SergeZ23. Thanks in advance!

@tfdahlin

Since somebody opened a new issue for the current 404 problems, I’m going to leave this issue closed and use that one instead.

@Dryrtan

python -m pip install --upgrade pytube should install the fix now. If there are further issues with v10.8.2, please open a new ticket so they get documented properly

Solved my problem, thanks friend

@HaltenStein

It still doesn’t work
from pytube import YouTube yt = YouTube('https://youtu.be/9bZkp7q19f0') print(yt.title)
HTTP Error 404: Not Found
pytube 10.9.3
python 3.9.5

@renan-eccel

It still doesn’t work for me either

@tfdahlin

@HaltenStein @renan-eccel the current 404 issue is a new issue. See #1060 for updates. I’m locking this thread because this particular 404 issue was resolved.

@pytube
pytube

locked as resolved and limited conversation to collaborators

Jul 26, 2021

Urllib.Error.Httperror: Http Error 404: Not Found With Code Examples

This article will demonstrate via examples how to resolve the Urllib.Error.Httperror: Http Error 404: Not Found error .

 try:
    urlopen(url)
except:
    pass

There is not just one way to solve a problem; rather, there are many different ways that can be tried. Urllib.Error.Httperror: Http Error 404: Not Found Further down, we will go over the remaining potential solutions.

get_object_or_404(OrderDetail, stripe_payment_intent=session.payment_intent)

As we have seen, the Urllib.Error.Httperror: Http Error 404: Not Found problemcode was solved by using a number of different instances.

How do I fix Error 403 Forbidden in Python?

You can try the following steps in order to resolve the 403 error in the browser try refreshing the page, rechecking the URL, clearing the browser cookies, check your user credentials.04-Apr-2022

Why does it say Error 404 Not Found?

A 404 error indicates that the webpage you’re trying to reach can’t be found. You might see a 404 error because of a problem with the website, because the page was moved or deleted, or because you typed the URL wrong.17-Nov-2020

How does Python handle 404 error?

Just catch HTTPError , handle it, and if it’s not Error 404, simply use raise to re-raise the exception. See the Python tutorial. can i do urllib2. urlopen(“*”) to handle any 404 errors and route them to my 404.

What HTTP 403 means?

The HTTP 403 Forbidden response status code indicates that the server understands the request but refuses to authorize it.08-Sept-2022

Why do I get 403 error?

The 403 Forbidden error appears when your server denies you permission to access a page on your site. This is mainly caused by a faulty security plugin, a corrupt . htaccess file, or incorrect file permissions on your server.20-Jul-2021

How do I fix error 404 in Chrome?

The simplest and easiest way to fix your 404 error code is to redirect the page to another one. You can perform this task using a 301 redirect. What’s 301, you may ask? It’s a redirect response code that signals a browser that the content has been transferred to another URL.

How do I debug a 404 error?

How to Fix the 404 Not Found Error

  • Retry the web page by pressing F5, clicking/tapping the refresh/reload button, or trying the URL from the address bar again.
  • Check for errors in the URL.
  • Move up one directory level at a time in the URL until you find something.
  • Search for the page from a popular search engine.

Which is the best way to get rid of a 404 error if a web page moved to another URL?

The best way to fix a 404 error is to redirect the broken URL to another, related URL.Part 1: How To Fix 404 Errors On Your Website

  • Redirect the 404 error somewhere else.
  • Correct the source link.
  • Restore deleted pages.
  • Ignore the not-found error.
  • Predict typos.

How do you handle HTTPError?

Use try and except to catch an HTTPError Create an except-statement with the syntax except requests. HTTPError as exception to catch an HTTPError under the variable name exception . If the code in the try-statement raises an HTTPError , the program continues to the except-statement. Alternatively, use urllib.

What is the 404 status code in Python?

status_code}”) # Status code is 404, meaning that resource doesn’t exist.

Уведомления

  • Начало
  • » Python для новичков
  • » парсинг python ошибка urllib.error.HTTPError: HTTP Error 404: Not Found

#1 Ноя. 16, 2017 16:13:50

парсинг python ошибка urllib.error.HTTPError: HTTP Error 404: Not Found

Есть сайт с фильтром данных по запросу на начальной странице. На ней (на начальной) странице тестовый код работает как и положено. При переходе на страницу результата не может открыть страницу. Причина в библиотеке или в свойствах сайта? Соответственно эта ссылка открывается в любом браузере без проблем.

 import urllib.request
from bs4 import BeautifulSoup
source = urllib.request.urlopen('http://...тратата')
soup = BeautifulSoup(source, "lxml")
for paragraf in soup.find_all('span'):
    print(paragraf.string)

Офлайн

  • Пожаловаться

#2 Ноя. 16, 2017 18:12:57

парсинг python ошибка urllib.error.HTTPError: HTTP Error 404: Not Found

Проблема может быть в том что у блоков span может и не быть параметров string. Посмотри HTML код страницы и проверь правильность поиска. Может быть тебе не span нужен, а какой нибудь div или a блоки.

Офлайн

  • Пожаловаться

#3 Ноя. 16, 2017 18:16:33

парсинг python ошибка urllib.error.HTTPError: HTTP Error 404: Not Found

damilkrose
Проблема может быть в том что у блоков span может и не быть параметров string. Посмотри HTML код страницы и проверь правильность поиска. Может быть тебе не span нужен, а какой нибудь div или a блоки.

Может быть, если ты пишешь for paragraph in soup.findall(‘span’), значит поиск по текстам. Может там не string а text, content. Не не – просто проверь исходный код.

P. S. Лично я вместо urllib3 юза requests. Он в принципе просто Упрощенный urllib, но с ним удобнее.

Офлайн

  • Пожаловаться

#4 Ноя. 16, 2017 18:24:16

парсинг python ошибка urllib.error.HTTPError: HTTP Error 404: Not Found

damilkrose
Какое это отношение имеет к ошибке 404?
Вы какой-то перманентный бред несете. То не к месту потоки приплетете, то на 404 виноват парсер. Давайте вы сначала думать будете, а потом раздавать советы?

Офлайн

  • Пожаловаться

#5 Ноя. 16, 2017 18:27:21

парсинг python ошибка urllib.error.HTTPError: HTTP Error 404: Not Found

ewro
Пока вы не скажите, какой УРЛ пытаетесь парсить, вам вряд ли помогут – нюансов может быть миллион, может их серверу куки не хватает? Как это проверить?

Офлайн

  • Пожаловаться

#6 Ноя. 16, 2017 19:35:07

парсинг python ошибка urllib.error.HTTPError: HTTP Error 404: Not Found

http://zakupki.gov.ru
Там в поиске что-нибудь вбить. Например, “закупки”.

Отредактировано ewro (Ноя. 16, 2017 19:36:59)

Офлайн

  • Пожаловаться

#7 Ноя. 18, 2017 08:32:51

парсинг python ошибка urllib.error.HTTPError: HTTP Error 404: Not Found

Надо попробовать Selenium. То ли это направление?

Офлайн

  • Пожаловаться

#8 Ноя. 18, 2017 08:36:40

парсинг python ошибка urllib.error.HTTPError: HTTP Error 404: Not Found

ewro
http://zakupki.gov.ruТам в поиске что-нибудь вбить. Например, “закупки”.

К сожалению там регламентные работы

Офлайн

  • Пожаловаться

#9 Ноя. 18, 2017 08:41:17

парсинг python ошибка urllib.error.HTTPError: HTTP Error 404: Not Found

Да, я видел уже. Скажите свое мнение о Selenium.

Офлайн

  • Пожаловаться

#10 Ноя. 18, 2017 08:52:43

парсинг python ошибка urllib.error.HTTPError: HTTP Error 404: Not Found

Я подозреваю, что моя проблема все же в библиотеке. И если, как я понял о Селениуме, он эмулирует браузер Chrome, например, то все должно получиться. При прочих равных условиях

Офлайн

  • Пожаловаться

  • Начало
  • » Python для новичков
  • » парсинг python ошибка urllib.error.HTTPError: HTTP Error 404: Not Found

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *