Urllib error httperror http error 404 not found

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

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:UsersznmcaVSCodeSpotify-Playlist-Downloaderpytubes.py", line 4, in <module>
    out_file = pytube.YouTube("https://www.youtube.com/watch?v=yHwGIA4VeOc").streams.first().download("D:Music")
  File "C:UsersznmcaAppDataLocalProgramsPythonPython39libsite-packagespytube__main__.py", line 308, in streams
    return StreamQuery(self.fmt_streams)
  File "C:UsersznmcaAppDataLocalProgramsPythonPython39libsite-packagespytube__main__.py", line 213, in fmt_streams
    if "adaptive_fmts" in self.player_config_args:
  File "C:UsersznmcaAppDataLocalProgramsPythonPython39libsite-packagespytube__main__.py", line 187, in player_config_args
    self._player_config_args = self.vid_info
  File "C:UsersznmcaAppDataLocalProgramsPythonPython39libsite-packagespytube__main__.py", line 278, in vid_info
    return dict(parse_qsl(self.vid_info_raw))
  File "C:UsersznmcaAppDataLocalProgramsPythonPython39libsite-packagespytube__main__.py", line 108, in vid_info_raw
    self._vid_info_raw = request.get(self.vid_info_url)
  File "C:UsersznmcaAppDataLocalProgramsPythonPython39libsite-packagespytuberequest.py", line 52, in get
    response = _execute_request(url, headers=extra_headers, timeout=timeout)
  File "C:UsersznmcaAppDataLocalProgramsPythonPython39libsite-packagespytuberequest.py", line 36, in _execute_request
    return urlopen(request, timeout=timeout)  # nosec
  File "C:UsersznmcaAppDataLocalProgramsPythonPython39liburllibrequest.py", line 214, in urlopen
    return opener.open(url, data, timeout)
  File "C:UsersznmcaAppDataLocalProgramsPythonPython39liburllibrequest.py", line 523, in open
    response = meth(req, response)
  File "C:UsersznmcaAppDataLocalProgramsPythonPython39liburllibrequest.py", line 632, in http_response
    response = self.parent.error(
  File "C:UsersznmcaAppDataLocalProgramsPythonPython39liburllibrequest.py", line 555, in error
    result = self._call_chain(*args)
  File "C:UsersznmcaAppDataLocalProgramsPythonPython39liburllibrequest.py", line 494, in _call_chain
    result = func(*args)
  File "C:UsersznmcaAppDataLocalProgramsPythonPython39liburllibrequest.py", line 747, in http_error_302
    return self.parent.open(new, timeout=req.timeout)
  File "C:UsersznmcaAppDataLocalProgramsPythonPython39liburllibrequest.py", line 523, in open
    response = meth(req, response)
  File "C:UsersznmcaAppDataLocalProgramsPythonPython39liburllibrequest.py", line 632, in http_response
    response = self.parent.error(
  File "C:UsersznmcaAppDataLocalProgramsPythonPython39liburllibrequest.py", line 561, in error
    return self._call_chain(*args)
  File "C:UsersznmcaAppDataLocalProgramsPythonPython39liburllibrequest.py", line 494, in _call_chain
    result = func(*args)
  File "C:UsersznmcaAppDataLocalProgramsPythonPython39liburllibrequest.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 DownloaderDownloadApp.pyw", line 54, in run
   result = self.fn(*self.args, **self.kwargs)
 File "X:Youtube DownloaderDownloadApp.pyw", line 174, in Download
   vids = yt.streams.filter(only_audio=True).all()
 File "C:UsersLAppDataLocalProgramsPythonPython39libsite-packagespytube__main__.py", line 308, in streams
   return StreamQuery(self.fmt_streams)
 File "C:UsersLAppDataLocalProgramsPythonPython39libsite-packagespytube__main__.py", line 213, in fmt_streams
   if "adaptive_fmts" in self.player_config_args:
 File "C:UsersLAppDataLocalProgramsPythonPython39libsite-packagespytube__main__.py", line 187, in player_config_args
   self._player_config_args = self.vid_info
 File "C:UsersLAppDataLocalProgramsPythonPython39libsite-packagespytube__main__.py", line 278, in vid_info
   return dict(parse_qsl(self.vid_info_raw))
 File "C:UsersLAppDataLocalProgramsPythonPython39libsite-packagespytube__main__.py", line 108, in vid_info_raw
   self._vid_info_raw = request.get(self.vid_info_url)
 File "C:UsersLAppDataLocalProgramsPythonPython39libsite-packagespytuberequest.py", line 52, in get
   response = _execute_request(url, headers=extra_headers, timeout=timeout)
 File "C:UsersLAppDataLocalProgramsPythonPython39libsite-packagespytuberequest.py", line 36, in _execute_request
   return urlopen(request, timeout=timeout)  # nosec
 File "C:UsersLAppDataLocalProgramsPythonPython39liburllibrequest.py", line 214, in urlopen
   return opener.open(url, data, timeout)
 File "C:UsersLAppDataLocalProgramsPythonPython39liburllibrequest.py", line 523, in open
   response = meth(req, response)
 File "C:UsersLAppDataLocalProgramsPythonPython39liburllibrequest.py", line 632, in http_response
   response = self.parent.error(
 File "C:UsersLAppDataLocalProgramsPythonPython39liburllibrequest.py", line 555, in error
   result = self._call_chain(*args)
 File "C:UsersLAppDataLocalProgramsPythonPython39liburllibrequest.py", line 494, in _call_chain
   result = func(*args)
 File "C:UsersLAppDataLocalProgramsPythonPython39liburllibrequest.py", line 747, in http_error_302
   return self.parent.open(new, timeout=req.timeout)
 File "C:UsersLAppDataLocalProgramsPythonPython39liburllibrequest.py", line 523, in open
   response = meth(req, response)
 File "C:UsersLAppDataLocalProgramsPythonPython39liburllibrequest.py", line 632, in http_response
   response = self.parent.error(
 File "C:UsersLAppDataLocalProgramsPythonPython39liburllibrequest.py", line 561, in error
   return self._call_chain(*args)
 File "C:UsersLAppDataLocalProgramsPythonPython39liburllibrequest.py", line 494, in _call_chain
   result = func(*args)
 File "C:UsersLAppDataLocalProgramsPythonPython39liburllibrequest.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:Userswilsonanaconda3envsbugfixlibsite-packagespytube__main__.py", line 308, in streams
    return StreamQuery(self.fmt_streams)
  File "C:Userswilsonanaconda3envsbugfixlibsite-packagespytube__main__.py", line 213, in fmt_streams
    if "adaptive_fmts" in self.player_config_args:
  File "C:Userswilsonanaconda3envsbugfixlibsite-packagespytube__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:UsersSergePycharmProjectsYoutubevenvlibsite-packagespytubestreams.py", line 261, in download
  max_retries=max_retries
File "C:UsersSergePycharmProjectsYoutubevenvlibsite-packagespytuberequest.py", line 160, in stream
  timeout=timeout
File "C:UsersSergePycharmProjectsYoutubevenvlibsite-packagespytuberequest.py", line 36, in _execute_request
  return urlopen(request, timeout=timeout)  # nosec
File "C:UsersSergeAppDataLocalProgramsPythonPython37-32liburllibrequest.py", line 222, in urlopen
  return opener.open(url, data, timeout)
File "C:UsersSergeAppDataLocalProgramsPythonPython37-32liburllibrequest.py", line 531, in open
  response = meth(req, response)
File "C:UsersSergeAppDataLocalProgramsPythonPython37-32liburllibrequest.py", line 641, in http_response
  'http', request, response, code, msg, hdrs)
File "C:UsersSergeAppDataLocalProgramsPythonPython37-32liburllibrequest.py", line 569, in error
  return self._call_chain(*args)
File "C:UsersSergeAppDataLocalProgramsPythonPython37-32liburllibrequest.py", line 503, in _call_chain
  result = func(*args)
File "C:UsersSergeAppDataLocalProgramsPythonPython37-32liburllibrequest.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:UsersSergePycharmProjectsYoutubevenvlibsite-packagespytubestreams.py", line 274, in download
  max_retries=max_retries
File "C:UsersSergePycharmProjectsYoutubevenvlibsite-packagespytuberequest.py", line 127, in seq_stream
  yield from stream(url, timeout=timeout, max_retries=max_retries)
File "C:UsersSergePycharmProjectsYoutubevenvlibsite-packagespytuberequest.py", line 160, in stream
  timeout=timeout
File "C:UsersSergePycharmProjectsYoutubevenvlibsite-packagespytuberequest.py", line 36, in _execute_request
  return urlopen(request, timeout=timeout)  # nosec
File "C:UsersSergeAppDataLocalProgramsPythonPython37-32liburllibrequest.py", line 222, in urlopen
  return opener.open(url, data, timeout)
File "C:UsersSergeAppDataLocalProgramsPythonPython37-32liburllibrequest.py", line 531, in open
  response = meth(req, response)
File "C:UsersSergeAppDataLocalProgramsPythonPython37-32liburllibrequest.py", line 641, in http_response
  'http', request, response, code, msg, hdrs)
File "C:UsersSergeAppDataLocalProgramsPythonPython37-32liburllibrequest.py", line 569, in error
  return self._call_chain(*args)
File "C:UsersSergeAppDataLocalProgramsPythonPython37-32liburllibrequest.py", line 503, in _call_chain
  result = func(*args)
File "C:UsersSergeAppDataLocalProgramsPythonPython37-32liburllibrequest.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

Introduction

You may also find useful the following article on fetching web resources with Python:

  • Basic Authentication — A tutorial on Basic Authentication, with examples in Python.

urllib.request is a Python module for fetching URLs (Uniform Resource Locators). It offers a very simple interface, in the form of the urlopen function. This is capable of fetching URLs using a variety of different protocols. It also offers a slightly more complex interface for handling common situations — like basic authentication, cookies, proxies and so on. These are provided by objects called handlers and openers.

urllib.request supports fetching URLs for many “URL schemes” (identified by the string before the ":" in URL — for example "ftp" is the URL scheme of "ftp://python.org/") using their associated network protocols (e.g. FTP, HTTP). This tutorial focuses on the most common case, HTTP.

For straightforward situations urlopen is very easy to use. But as soon as you encounter errors or non-trivial cases when opening HTTP URLs, you will need some understanding of the HyperText Transfer Protocol. The most comprehensive and authoritative reference to HTTP is RFC 2616. This is a technical document and not intended to be easy to read. This HOWTO aims to illustrate using urllib, with enough detail about HTTP to help you through. It is not intended to replace the urllib.request docs, but is supplementary to them.

Fetching URLs

The simplest way to use urllib.request is as follows:

import urllib.request
with urllib.request.urlopen('http://python.org/') as response:
   html = response.read()

If you wish to retrieve a resource via URL and store it in a temporary location, you can do so via the shutil.copyfileobj() and tempfile.NamedTemporaryFile() functions:

import shutil
import tempfile
import urllib.request

with urllib.request.urlopen('http://python.org/') as response:
    with tempfile.NamedTemporaryFile(delete=False) as tmp_file:
        shutil.copyfileobj(response, tmp_file)

with open(tmp_file.name) as html:
    pass

Many uses of urllib will be that simple (note that instead of an ‘http:’ URL we could have used a URL starting with ‘ftp:’, ‘file:’, etc.). However, it’s the purpose of this tutorial to explain the more complicated cases, concentrating on HTTP.

HTTP is based on requests and responses — the client makes requests and servers send responses. urllib.request mirrors this with a Request object which represents the HTTP request you are making. In its simplest form you create a Request object that specifies the URL you want to fetch. Calling urlopen with this Request object returns a response object for the URL requested. This response is a file-like object, which means you can for example call .read() on the response:

import urllib.request

req = urllib.request.Request('http://www.voidspace.org.uk')
with urllib.request.urlopen(req) as response:
   the_page = response.read()

Note that urllib.request makes use of the same Request interface to handle all URL schemes. For example, you can make an FTP request like so:

req = urllib.request.Request('ftp://example.com/')

In the case of HTTP, there are two extra things that Request objects allow you to do: First, you can pass data to be sent to the server. Second, you can pass extra information (“metadata”) about the data or the about request itself, to the server — this information is sent as HTTP “headers”. Let’s look at each of these in turn.

Data

Sometimes you want to send data to a URL (often the URL will refer to a CGI (Common Gateway Interface) script or other web application). With HTTP, this is often done using what’s known as a POST request. This is often what your browser does when you submit a HTML form that you filled in on the web. Not all POSTs have to come from forms: you can use a POST to transmit arbitrary data to your own application. In the common case of HTML forms, the data needs to be encoded in a standard way, and then passed to the Request object as the data argument. The encoding is done using a function from the urllib.parse library.

import urllib.parse
import urllib.request

url = 'http://www.someserver.com/cgi-bin/register.cgi'
values = {'name' : 'Michael Foord',
          'location' : 'Northampton',
          'language' : 'Python' }

data = urllib.parse.urlencode(values)
data = data.encode('ascii') # data should be bytes
req = urllib.request.Request(url, data)
with urllib.request.urlopen(req) as response:
   the_page = response.read()

Note that other encodings are sometimes required (e.g. for file upload from HTML forms — see HTML Specification, Form Submission for more details).

If you do not pass the data argument, urllib uses a GET request. One way in which GET and POST requests differ is that POST requests often have “side-effects”: they change the state of the system in some way (for example by placing an order with the website for a hundredweight of tinned spam to be delivered to your door). Though the HTTP standard makes it clear that POSTs are intended to always cause side-effects, and GET requests never to cause side-effects, nothing prevents a GET request from having side-effects, nor a POST requests from having no side-effects. Data can also be passed in an HTTP GET request by encoding it in the URL itself.

This is done as follows:

>>> import urllib.request
>>> import urllib.parse
>>> data = {}
>>> data['name'] = 'Somebody Here'
>>> data['location'] = 'Northampton'
>>> data['language'] = 'Python'
>>> url_values = urllib.parse.urlencode(data)
>>> print(url_values)  # The order may differ from below.  
name=Somebody+Here&language=Python&location=Northampton
>>> url = 'http://www.example.com/example.cgi'
>>> full_url = url + '?' + url_values
>>> data = urllib.request.urlopen(full_url)

Notice that the full URL is created by adding a ? to the URL, followed by the encoded values.

Headers

We’ll discuss here one particular HTTP header, to illustrate how to add headers to your HTTP request.

Some websites (Google for example) dislike being browsed by programs, or send different versions to different browsers (Browser sniffing is a very bad practice for website design — building sites using web standards is much more sensible. Unfortunately a lot of sites still send different versions to different browsers.). By default urllib identifies itself as Python-urllib/x.y (where x and y are the major and minor version numbers of the Python release, e.g. Python-urllib/2.5), which may confuse the site, or just plain not work. The way a browser identifies itself is through the User-Agent header (The user agent for MSIE 6 is ‘Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322)’). When you create a Request object you can pass a dictionary of headers in. The following example makes the same request as above, but identifies itself as a version of Internet Explorer.

For details of more HTTP request headers, see Quick Reference to HTTP Headers.import urllib.parse

import urllib.request

url = 'http://www.someserver.com/cgi-bin/register.cgi'
user_agent = 'Mozilla/5.0 (Windows NT 6.1; Win64; x64)'
values = {'name': 'Michael Foord',
          'location': 'Northampton',
          'language': 'Python' }
headers = {'User-Agent': user_agent}

data = urllib.parse.urlencode(values)
data = data.encode('ascii')
req = urllib.request.Request(url, data, headers)
with urllib.request.urlopen(req) as response:
   the_page = response.read()

The response also has two useful methods. See the section on info and geturl which comes after we have a look at what happens when things go wrong.

Handling Exceptions

urlopen raises URLError when it cannot handle a response (though as usual with Python APIs, built-in exceptions such as ValueError, TypeError etc. may also be raised).

HTTPError is the subclass of URLError raised in the specific case of HTTP URLs.

The exception classes are exported from the urllib.error module.

URLError

Often, URLError is raised because there is no network connection (no route to the specified server), or the specified server doesn’t exist. In this case, the exception raised will have a ‘reason’ attribute, which is a tuple containing an error code and a text error message.

e.g.

>>> req = urllib.request.Request('http://www.pretend_server.org')
>>> try: urllib.request.urlopen(req)
... except urllib.error.URLError as e:
...     print(e.reason)      
...
(4, 'getaddrinfo failed')

HTTPError

Every HTTP response from the server contains a numeric “status code”. Sometimes the status code indicates that the server is unable to fulfil the request. The default handlers will handle some of these responses for you (for example, if the response is a “redirection” that requests the client fetch the document from a different URL, urllib will handle that for you). For those it can’t handle, urlopen will raise an HTTPError. Typical errors include ‘404’ (page not found), ‘403’ (request forbidden), and ‘401’ (authentication required).

See section 10 of RFC 2616 for a reference on all the HTTP error codes.

The HTTPError instance raised will have an integer ‘code’ attribute, which corresponds to the error sent by the server.

Error Codes

Because the default handlers handle redirects (codes in the 300 range), and codes in the 100–299 range indicate success, you will usually only see error codes in the 400–599 range.

http.server.BaseHTTPRequestHandler.responses is a useful dictionary of response codes in that shows all the response codes used by RFC 2616. The dictionary is reproduced here for convenience

# Table mapping response codes to messages; entries have the
# form {code: (shortmessage, longmessage)}.
responses = {
    100: ('Continue', 'Request received, please continue'),
    101: ('Switching Protocols',
          'Switching to new protocol; obey Upgrade header'),

    200: ('OK', 'Request fulfilled, document follows'),
    201: ('Created', 'Document created, URL follows'),
    202: ('Accepted',
          'Request accepted, processing continues off-line'),
    203: ('Non-Authoritative Information', 'Request fulfilled from cache'),
    204: ('No Content', 'Request fulfilled, nothing follows'),
    205: ('Reset Content', 'Clear input form for further input.'),
    206: ('Partial Content', 'Partial content follows.'),

    300: ('Multiple Choices',
          'Object has several resources -- see URI list'),
    301: ('Moved Permanently', 'Object moved permanently -- see URI list'),
    302: ('Found', 'Object moved temporarily -- see URI list'),
    303: ('See Other', 'Object moved -- see Method and URL list'),
    304: ('Not Modified',
          'Document has not changed since given time'),
    305: ('Use Proxy',
          'You must use proxy specified in Location to access this '
          'resource.'),
    307: ('Temporary Redirect',
          'Object moved temporarily -- see URI list'),

    400: ('Bad Request',
          'Bad request syntax or unsupported method'),
    401: ('Unauthorized',
          'No permission -- see authorization schemes'),
    402: ('Payment Required',
          'No payment -- see charging schemes'),
    403: ('Forbidden',
          'Request forbidden -- authorization will not help'),
    404: ('Not Found', 'Nothing matches the given URI'),
    405: ('Method Not Allowed',
          'Specified method is invalid for this server.'),
    406: ('Not Acceptable', 'URI not available in preferred format.'),
    407: ('Proxy Authentication Required', 'You must authenticate with '
          'this proxy before proceeding.'),
    408: ('Request Timeout', 'Request timed out; try again later.'),
    409: ('Conflict', 'Request conflict.'),
    410: ('Gone',
          'URI no longer exists and has been permanently removed.'),
    411: ('Length Required', 'Client must specify Content-Length.'),
    412: ('Precondition Failed', 'Precondition in headers is false.'),
    413: ('Request Entity Too Large', 'Entity is too large.'),
    414: ('Request-URI Too Long', 'URI is too long.'),
    415: ('Unsupported Media Type', 'Entity body in unsupported format.'),
    416: ('Requested Range Not Satisfiable',
          'Cannot satisfy request range.'),
    417: ('Expectation Failed',
          'Expect condition could not be satisfied.'),

    500: ('Internal Server Error', 'Server got itself in trouble'),
    501: ('Not Implemented',
          'Server does not support this operation'),
    502: ('Bad Gateway', 'Invalid responses from another server/proxy.'),
    503: ('Service Unavailable',
          'The server cannot process the request due to a high load'),
    504: ('Gateway Timeout',
          'The gateway server did not receive a timely response'),
    505: ('HTTP Version Not Supported', 'Cannot fulfill request.'),
    }

When an error is raised the server responds by returning an HTTP error code and an error page. You can use the HTTPError instance as a response on the page returned. This means that as well as the code attribute, it also has read, geturl, and info, methods as returned by the urllib.response module:

>>> req = urllib.request.Request('http://www.python.org/fish.html')
>>> try:
...     urllib.request.urlopen(req)
... except urllib.error.HTTPError as e:
...     print(e.code)
...     print(e.read())  
...
404
b'<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">nnn<html
  ...
  <title>Page Not Found</title>n
  ...

Wrapping it Up

So if you want to be prepared for HTTPError or URLError there are two basic approaches. I prefer the second approach.

Number 1

from urllib.request import Request, urlopen
from urllib.error import URLError, HTTPError
req = Request(someurl)
try:
    response = urlopen(req)
except HTTPError as e:
    print('The server couldn't fulfill the request.')
    print('Error code: ', e.code)
except URLError as e:
    print('We failed to reach a server.')
    print('Reason: ', e.reason)
else:
    # everything is fine

Note

The except HTTPError must come first, otherwise except URLError will also catch an HTTPError.

Number 2

from urllib.request import Request, urlopen
from urllib.error import URLError
req = Request(someurl)
try:
    response = urlopen(req)
except URLError as e:
    if hasattr(e, 'reason'):
        print('We failed to reach a server.')
        print('Reason: ', e.reason)
    elif hasattr(e, 'code'):
        print('The server couldn't fulfill the request.')
        print('Error code: ', e.code)
else:
    # everything is fine

info and geturl

The response returned by urlopen (or the HTTPError instance) has two useful methods info() and geturl() and is defined in the module urllib.response..

geturl — this returns the real URL of the page fetched. This is useful because urlopen (or the opener object used) may have followed a redirect. The URL of the page fetched may not be the same as the URL requested.

info — this returns a dictionary-like object that describes the page fetched, particularly the headers sent by the server. It is currently an http.client.HTTPMessage instance.

Typical headers include ‘Content-length’, ‘Content-type’, and so on. See the Quick Reference to HTTP Headers for a useful listing of HTTP headers with brief explanations of their meaning and use.

Openers and Handlers

When you fetch a URL you use an opener (an instance of the perhaps confusingly-named urllib.request.OpenerDirector). Normally we have been using the default opener — via urlopen — but you can create custom openers. Openers use handlers. All the “heavy lifting” is done by the handlers. Each handler knows how to open URLs for a particular URL scheme (http, ftp, etc.), or how to handle an aspect of URL opening, for example HTTP redirections or HTTP cookies.

You will want to create openers if you want to fetch URLs with specific handlers installed, for example to get an opener that handles cookies, or to get an opener that does not handle redirections.

To create an opener, instantiate an OpenerDirector, and then call .add_handler(some_handler_instance) repeatedly.

Alternatively, you can use build_opener, which is a convenience function for creating opener objects with a single function call. build_opener adds several handlers by default, but provides a quick way to add more and/or override the default handlers.

Other sorts of handlers you might want to can handle proxies, authentication, and other common but slightly specialised situations.

install_opener can be used to make an opener object the (global) default opener. This means that calls to urlopen will use the opener you have installed.

Opener objects have an open method, which can be called directly to fetch urls in the same way as the urlopen function: there’s no need to call install_opener, except as a convenience.

Basic Authentication

To illustrate creating and installing a handler we will use the HTTPBasicAuthHandler. For a more detailed discussion of this subject – including an explanation of how Basic Authentication works — see the Basic Authentication Tutorial.

When authentication is required, the server sends a header (as well as the 401 error code) requesting authentication. This specifies the authentication scheme and a ‘realm’. The header looks like: WWW-Authenticate: SCHEME realm="REALM".

e.g.

WWW-Authenticate: Basic realm="cPanel Users"

The client should then retry the request with the appropriate name and password for the realm included as a header in the request. This is ‘basic authentication’. In order to simplify this process we can create an instance of HTTPBasicAuthHandler and an opener to use this handler.

The HTTPBasicAuthHandler uses an object called a password manager to handle the mapping of URLs and realms to passwords and usernames. If you know what the realm is (from the authentication header sent by the server), then you can use a HTTPPasswordMgr. Frequently one doesn’t care what the realm is. In that case, it is convenient to use HTTPPasswordMgrWithDefaultRealm. This allows you to specify a default username and password for a URL. This will be supplied in the absence of you providing an alternative combination for a specific realm. We indicate this by providing None as the realm argument to the add_password method.

The top-level URL is the first URL that requires authentication. URLs “deeper” than the URL you pass to .add_password() will also match.

# create a password manager
password_mgr = urllib.request.HTTPPasswordMgrWithDefaultRealm()

# Add the username and password.
# If we knew the realm, we could use it instead of None.
top_level_url = "http://example.com/foo/"
password_mgr.add_password(None, top_level_url, username, password)

handler = urllib.request.HTTPBasicAuthHandler(password_mgr)

# create "opener" (OpenerDirector instance)
opener = urllib.request.build_opener(handler)

# use the opener to fetch a URL
opener.open(a_url)

# Install the opener.
# Now all calls to urllib.request.urlopen use our opener.
urllib.request.install_opener(opener)

Note

In the above example we only supplied our HTTPBasicAuthHandler to build_opener. By default openers have the handlers for normal situations – ProxyHandler (if a proxy setting such as an http_proxy environment variable is set), UnknownHandler, HTTPHandler, HTTPDefaultErrorHandler, HTTPRedirectHandler, FTPHandler, FileHandler, DataHandler, HTTPErrorProcessor.

top_level_url is in fact either a full URL (including the ‘http:’ scheme component and the hostname and optionally the port number) e.g. "http://example.com/" or an “authority” (i.e. the hostname, optionally including the port number) e.g. "example.com" or "example.com:8080" (the latter example includes a port number). The authority, if present, must NOT contain the “userinfo” component — for example "joe:password@example.com" is not correct.

Proxies

urllib will auto-detect your proxy settings and use those. This is through the ProxyHandler, which is part of the normal handler chain when a proxy setting is detected. Normally that’s a good thing, but there are occasions when it may not be helpful.

urllib opener for SSL proxy (CONNECT method): ASPN Cookbook Recipe

One way to do this is to setup our own ProxyHandler, with no proxies defined. This is done using similar steps to setting up a Basic Authentication handler:

>>> proxy_support = urllib.request.ProxyHandler({})
>>> opener = urllib.request.build_opener(proxy_support)
>>> urllib.request.install_opener(opener)

Note

Currently urllib.request does not support fetching of https locations through a proxy. However, this can be enabled by extending urllib.request as shown in the recipe.

urllib opener for SSL proxy (CONNECT method): ASPN Cookbook Recipe.

Note

HTTP_PROXY will be ignored if a variable REQUEST_METHOD is set; see the documentation on getproxies().

Sockets and Layers

The Python support for fetching resources from the web is layered. urllib uses the http.client library, which in turn uses the socket library.

As of Python 2.3 you can specify how long a socket should wait for a response before timing out. This can be useful in applications which have to fetch web pages. By default the socket module has no timeout and can hang. Currently, the socket timeout is not exposed at the http.client or urllib.request levels. However, you can set the default timeout globally for all sockets using

import socket
import urllib.request

# timeout in seconds
timeout = 10
socket.setdefaulttimeout(timeout)

# this call to urllib.request.urlopen now uses the default timeout
# we have set in the socket module
req = urllib.request.Request('http://www.voidspace.org.uk')
response = urllib.request.urlopen(req)

Понравилась статья? Поделить с друзьями:
  • Urllib error httperror http error 403 forbidden python
  • Urllib error httperror http error 401 unauthorized
  • Urllib error httperror http error 400 bad request
  • Urlerror urlopen error errno 11001 getaddrinfo failed
  • Urlerror urlopen error errno 104 connection reset by peer