+3 votes
in Programming Languages by (1.9k points)
I want to check the HTTP response code before reading the data from a URL? What python module should I use for this?

1 Answer

0 votes
by (25.6k points)

You can use either requests or urllib module to get the HTTP response code from a URL.

Here is an example that shows how to use these modules:

Using requests

import requests
url = "https://www.discoverbits.in/"
try:
    req = requests.head(url)
    print(req.status_code)
except requests.ConnectionError as e:
    print(e)

Using urllib

from urllib.error import URLError
import urllib.request

url = "https://www.discoverbits.in/"
try:
    conn = urllib.request.urlopen(url)
    print(conn.getcode())
except urllib.error.URLError as e:
    print(e)

...