urllib status code in python

To get the status code of a webpage using urllib in Python, you can make use of the urlopen function from urllib.request module and retrieve the status code using the HTTPResponse object.

Here's an example:

main.py
from urllib.request import urlopen

url = "https://www.google.com"
response = urlopen(url)
status_code = response.getcode()

print(f"Status Code: {status_code}")
162 chars
8 lines

This code first imports urlopen function from urllib.request module. It then defines the url variable to the desired webpage.

The urlopen function is called with the url variable as its argument to request the webpage. The response received is stored in response object.

Finally, the getcode() method is used to retrieve the status code from response. It is then printed on the console.

This code can be easily extended to handle error conditions as well.

related categories

gistlibby LogSnag