+3 votes
in Programming Languages by (40.5k 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

+1 vote
by (349k points)
selected by
 
Best answer

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://qa.tellustheanswer.com/"
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://qa.tellustheanswer.com/"
try:
    conn = urllib.request.urlopen(url)
    print(conn.getcode())
except urllib.error.URLError as e:
    print(e)

Related questions


...