Ошибка 404 python

Look at the r.status_code attribute:

if r.status_code == 404:
    # A 404 was issued.

Demo:

>>> import requests
>>> r = requests.get('http://httpbin.org/status/404')
>>> r.status_code
404

If you want requests to raise an exception for error codes (4xx or 5xx), call r.raise_for_status():

>>> r = requests.get('http://httpbin.org/status/404')
>>> r.raise_for_status()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "requests/models.py", line 664, in raise_for_status
    raise http_error
requests.exceptions.HTTPError: 404 Client Error: NOT FOUND
>>> r = requests.get('http://httpbin.org/status/200')
>>> r.raise_for_status()
>>> # no exception raised.

You can also test the response object in a boolean context; if the status code is not an error code (4xx or 5xx), it is considered ‘true’:

if r:
    # successful response

If you want to be more explicit, use if r.ok:.

Prerequisite: Creating simple application in Flask

A 404 Error is showed whenever a page is not found. Maybe the owner changed its URL and forgot to change the link or maybe they deleted the page itself. Every site needs a Custom Error page to avoid the user to see the default Ugly Error page.

GeeksforGeeks also has a customized error page. If we type a URL like
www.geeksforgeeks.org/ajneawnewiaiowjf

Default 404 Error

GeeksForGeeks Customized Error Page

It will show an Error 404 page since this URL doesn’t exist. But an error page provides a beautiful layout, helps the user to go back, or even takes them to the homepage after a specific time interval. That is why Custom Error pages are necessary for every website.

Flask provides us with a way to handle the error and return our Custom Error page.

For this, we need to download and import flask. Download the flask through the following commands on CMD.

pip install flask

Using app.py as our Python file to manage templates, 404.html be the file we will return in the case of a 404 error and header.html be the file with header and navbar of a website.

app.py
Flask allows us to make a python file to define all routes and functions. In app.py we have defined the route to the main page (‘/’) and error handler function which is a flask function and we passed 404 error as a parameter.

from flask import Flask, render_template

app = Flask(__name__)

@app.errorhandler(404)

def not_found(e):

  return render_template("404.html")

The above python program will return 404.html file whenever the user opens a broken link.

404.html
The following code exports header and navbar from header.html.
Both files should be stored in templates folder according to the flask.

{% extends "header.html" %}

{% block title %}Page Not Found{% endblock %}

{% block body %}

  <h1>Oops! Looks like the page doesn't exist anymore</h1>

  <a href="{{ url_for('index') }}"><p>Click Here</a>To go to the Home Page</p>

{% endblock %}

Automatically Redirecting to the Home page after 5 seconds

The app.py code for this example stays the same as above.
The following code Shows the Custom 404 Error page and starts a countdown of 5 seconds.
After 5 seconds are completed, it redirects the user back to the homepage.
404.html
The following code exports header and navbar from header.html.
Both files should be stored in the templates folder according to the flask.
After 5 seconds, the user will get redirected to the Home Page Automatically.

<html>

<head>

<title>Page Not Found</title>

<script language="JavaScript" type="text/javascript">

var seconds =6;

// countdown timer. took 6 because page takes approx 1 sec to load

var url="{{url_for(index)}}";

// variable for index.html url

function redirect(){

 if (seconds <=0){

 // redirect to new url after counter  down.

  window.location = url;

 } else {

  seconds--;

  document.getElementById("pageInfo").innerHTML="Redirecting to Home Page after "

+seconds+" seconds."

  setTimeout("redirect()", 1000)

 }

}

</script>

</head>

{% extends "header.html" %}

//exporting navbar and header from header.html

{% block body %}

 <body onload="redirect()">

<p id="pageInfo"></p>

{% endblock %}

</html>

Sample header.html
This is a sample header.html which includes a navbar just like shown in the image.
It’s made up of bootstrap. You can also make one of your own.
For this one, refer the bootstrap documentation.

<!DOCTYPE html>

<html>

<head>

css/bootstrap.min.css"

 integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E26 

3XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

    <title>Flask</title>

</head>

<body>

"sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" 

crossorigin="anonymous"></script>

/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K

/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>

 integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl"

 crossorigin="anonymous"></script>

<header>

    <nav class="navbar navbar-expand-lg navbar-light bg-light">

  <a class="navbar-brand" href="#">Navbar</a>

  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target=

"#navbarSupportedContent" aria-controls="navbarSupportedContent"

 aria-expanded="false"  aria-label="Toggle navigation">

    <span class="navbar-toggler-icon"></span>

  </button>

  <div class="collapse navbar-collapse" id="navbarSupportedContent">

    <ul class="navbar-nav mr-auto">

      <li class="nav-item active">

        <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>

      </li>

      <li class="nav-item">

        <a class="nav-link" href="#">Link</a>

      </li>

      <li class="nav-item dropdown">

        <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown"

 role="button data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">

          Dropdown

        </a>

        <div class="dropdown-menu" aria-labelledby="navbarDropdown">

          <a class="dropdown-item" href="#">Action</a>

          <a class="dropdown-item" href="#">Another action</a>

          <div class="dropdown-divider"></div>

          <a class="dropdown-item" href="#">Something else here</a>

        </div>

      </li>

      <li class="nav-item">

        <a class="nav-link disabled" href="#">Disabled</a>

      </li>

    </ul>

    <form class="form-inline my-2 my-lg-0">

      <input class="form-control mr-sm-2" type="search"

       placeholder="Search" aria-label="Search">

      <button class="btn btn-outline-success my-2 my-sm-0" 

      type="submit">Search</button>

    </form>

  </div>

</nav>

</head>

 <body >

  {%block body%}

  {%endblock%}

</body>

</html>

Output:
The output will be a custom error page with header.html that the user exported.
The following is an example output with my custom header, footer, and 404.html file.

Last Updated :
15 Oct, 2020

Like Article

Save Article

Hi guys! In this tutorial, we will learn how to catch an HTTP 404 error in Python. There are many instances when we encounter an HTTP error with error code 404 on the internet. This error indicates that the requested page was not found. This tutorial will teach you how you can use Python to spot pages with such an error. Let’s see more on this with example programs.

Catch HTTP 404 error in Python

There are many methods for catching a 404 error. We will import the urllib or urllib3 library in this post for catching a 404 error. These library has required methods and attributes for our purpose. Let’s see the code and understand how it’s done.

Method 1

See the below example to find out a page with an HTTP 404 error.

import urllib3

http = urllib3.PoolManager()
error = http.request("GET", "https://www.google.com/404")
if (error.status == 404):
    print("HTTP 404 ERROR")

The output for the above code is:

HTTP 404 ERROR

In the above example, we have used the PoolManager of urllib3 to create an http object. A PoolManager instance is needed to make requests. Then we have used the request method to get an HTTPResponse object for the web page ‘https://www.google.com/404’. This HTTPResponse object contains status, data, and header. We check whether the status for this page is 404 if so we print that this is an HTTP error.

Method 2

In this method, we will import the Python urllib library. Have a look at the given code and try to understand.

import urllib.request, urllib.error

try:
    con = urllib.request.urlopen('http://www.google.com/404')

except urllib.error.HTTPError as err:
    print('HTTP', err.code, 'ERROR')

The output of the program:

HTTP 404 ERROR

As you can see, the urlopen() method opens the given URL for us. We have used try and except blocks to catch the HTTP error using urllib.error.HTTPError. If any error is raised while opening the URL, the control is given to except block and there we print the error code for HTTP error.

Thank you.

Also read: How to handle an attribute error in Python

Python request module is a simple and elegant Python HTTP library. It provides methods for accessing Web resources via HTTP. In the following article, we will use the HTTP GET method in the Request module. This method requests data from the server and the Exception handling comes in handy when the response is not successful. Here, we will go through such situations. We will use Python’s try and except functionality to explore the exceptions that arise from the Requests module.

  • url: Returns the URL of the response
  • raise_for_status(): If an error occur, this method returns a HTTPError object
  • request: Returns the request object that requested this response
  • status_code: Returns a number that indicates the status (200 is OK, 404 is Not Found)
     

Successful Connection Request

The first thing to know is that the response code is 200 if the request is successful.

Python3

Output:

200

Exception Handling for HTTP Errors

Here, we tried the following URL sequence and then passed this variable to the Python requests module using raised_for_status(). If the try part is successful, we will get the response code 200, if the page that we requested doesn’t exist. This is an HTTP error, which was handled by the Request module’s exception HTTPError and you probably got the error 404.

Python3

import requests

try:

    r = requests.get(url, timeout=1)

    r.raise_for_status()

except requests.exceptions.HTTPError as errh:

    print("HTTP Error")

    print(errh.args[0])

print(r)

Output:

HTTP Error
404 Client Error: Not Found for url: https://www.amazon.com/nothing_here
<Response [404]>

General Exception Handling

You could also use a general exception from the Request module. That is requests.exceptions.RequestException.

Python3

try:

    r = requests.get(url, timeout=1)

    r.raise_for_status()

except requests.exceptions.RequestException as errex:

    print("Exception request")

Output:

Exception request 

Now, you may have noticed that there is an argument ‘timeout’ passed into the Request module. We could prescribe a time limit for the requested connection to respond. If this has not happened, we could catch that using the exception requests.exceptions.ReadTimeout. To demonstrate this let us find a website that responds successfully.

Python3

import requests

try:

    r = requests.get(url, timeout=1)

    r.raise_for_status()

except requests.exceptions.ReadTimeout as errrt:

    print("Time out")

print(r)

Output:

<Response [200]>

If we change timeout = 0.01, the same code would return, because the request could not possibly be that fast.

Time out
<Response [200]>

Exception Handling for Missing Schema

Another common error is that we might not specify HTTPS or HTTP in the URL. For example, We cause use requests.exceptions.MissingSchema to catch this exception.

Python3

url = "www.google.com"

try:

    r = requests.get(url, timeout=1)

    r.raise_for_status()

except requests.exceptions.MissingSchema as errmiss:

    print("Missing schema: include http or https")

except requests.exceptions.ReadTimeout as errrt:

    print("Time out")

Output:

Missing scheme: include http or https

Exception Handling for Connection Error

Let us say that there is a site that doesn’t exist. Here, the error will occur even when you can’t make a connection because of the lack of an internet connection

Python3

try:

  r = requests.get(url, timeout = 1, verify = True)

  r.raise_for_status()

except requests.exceptions.HTTPError as errh:

  print("HTTP Error")

  print(errh.args[0])

except requests.exceptions.ReadTimeout as errrt:

  print("Time out")

except requests.exceptions.ConnectionError as conerr:

  print("Connection error")

Output:

Connection error

Putting Everything Together

Here, We put together everything we tried so far the idea is that the exceptions are handled according to the specificity. 

For example, url =  “https://www.gle.com”,  When this code is run for this URL will produce an Exception request. Whereas, In the absence of connection requests.exceptions.ConnectionError will print the Connection Error, and when the connection is not made the general exception is handled by requests.exceptions.RequestException.

Python3

try:

    r = requests.get(url, timeout=1, verify=True)

    r.raise_for_status()

except requests.exceptions.HTTPError as errh:

    print("HTTP Error")

    print(errh.args[0])

except requests.exceptions.ReadTimeout as errrt:

    print("Time out")

except requests.exceptions.ConnectionError as conerr:

    print("Connection error")

except requests.exceptions.RequestException as errex:

    print("Exception request")

Output:

Note: The output may change according to requests.

 Time out

Last Updated :
23 Jan, 2023

Like Article

Save Article

The urllib.error.HTTPError is a class in the Python urllib library that represents an HTTP error. An HTTPError is raised when an HTTP request returns a status code that represents an error, such as 4xx (client error) or 5xx (server error).

HTTPError Attributes

The urllib.error.HTTPError class has the following attributes:

  • code: The HTTP status code of the error.
  • reason: The human-readable reason phrase associated with the status code.
  • headers: The HTTP response headers for the request that caused the HTTPError.

What Causes HTTPError

Here are some common reasons why an HTTPError might be raised:

  • Invalid or malformed request URL.
  • Invalid or malformed request parameters or body.
  • Invalid or missing authentication credentials.
  • Server internal error or malfunction.
  • Server temporarily unavailable due to maintenance or overload.

Python HTTPError Examples

Here are a few examples of HTTP errors in Python:

404 Not Found


import urllib.request
import urllib.error

try:
    response = urllib.request.urlopen('http://httpbin.org/status/404')
except urllib.error.HTTPError as err:
    print(f'A HTTPError was thrown: {err.code} {err.reason}')

In the above example, an invalid URL is attempted to be opened using the urllib.request.urlopen() function. Running the above code raises an HTTPError with code 404:


A HTTPError was thrown: 404 NOT FOUND

400 Bad Request


import urllib.request

try:
    response = urllib.request.urlopen('http://httpbin.org/status/400')
except urllib.error.HTTPError as err:
    if err.code == 400:
        print('Bad request!')
    else:
        print(f'An HTTP error occurred: {err}')

In the above example, a bad request is sent to the server. Running the above code raises a HTTPError with code 400:


Bad request!

401 Unauthorized


import urllib.request
import urllib.error

try:
    response = urllib.request.urlopen('http://httpbin.org/status/401')
except urllib.error.HTTPError as err:
    if err.code == 401:
        print('Unauthorized!')
    else:
        print(f'An HTTP error occurred: {err}')

In the above example, a request is sent to the server with missing credentials. Running the above code raises a HTTPError with code 401:


Unauthorized!

500 Internal Server Error


import urllib.request
import urllib.error

try:
    response = urllib.request.urlopen('http://httpbin.org/status/500')
except urllib.error.HTTPError as err:
    if err.code == 500:
        print('Internal server error!')
    else:
        print(f'An HTTP error occurred: {err}')

In the above example, the server experiences an error internally. Running the above code raises a HTTPError with code 500:


Internal server error!

How to Fix HTTPError in Python

To fix HTTP errors in Python, the following steps can be taken:

  1. Check the network connection and ensure it is stable and working.
  2. Check the URL being accessed and make sure it is correct and properly formatted.
  3. Check the request parameters and body to ensure they are valid and correct.
  4. Check whether the request requires authentication credentials and make sure they are included in the request and are correct.
  5. If the request and URL are correct, check the HTTP status code and reason returned in the error message. This can give more information about the error.
  6. Try adding error handling code for the specific error. For example, the request can be attempted again or missing parameters can be added to the request.

Track, Analyze and Manage Errors With Rollbar

Managing errors and exceptions in your code is challenging. It can make deploying production code an unnerving experience. Being able to track, analyze, and manage errors in real-time can help you to proceed with more confidence. Rollbar automates error monitoring and triaging, making fixing Python errors easier than ever. Try it today!

Понравилась статья? Поделить с друзьями:
  • Ошибка 404 phpmyadmin apache
  • Ошибка 404 page not found
  • Ошибка 404 not found что это значит
  • Ошибка 404 not found перевод
  • Ошибка 404 not found nginx