Printing a domain that does not exist

Question:

Is there a way where I can print out that the domain does not exist instead of giving me an error like this

ConnectionError: HTTPSConnectionPool(host=’www.enroll.connect.web.co.id’, port=443): Max retries exceeded with url: / (Caused by NewConnectionError(‘<urllib3.connection.HTTPSConnection object at 0x7f4f558003d0>: Failed to establish a new connection: [Errno -2] Name or service not known’))

This is the code that i use to check whether the domain exist or not

request = requests.get('https://www.enroll.connect.web.co.id')
if request.status_code == 200:
    print('Web site exists')
else:
    print('Web site does not exist')

The logic should’ve been if the status is 200 then that means the website existed, but if it’s not 200 it should’ve print out that the website does not exist.

Thx!

Asked By: Derrell Hasan

||

Answers:

Use Exception Handling:
code:

import requests

try:
    request = requests.get('https://www.enroll.connect.web.co.id')
    if request.status_code == 200:
        print('Web site exists')
except :       
    print('Web site does not exist')
Answered By: Mehmaam

In this case I prefer to use an exception and just bypass it

import requests
try:
    request = requests.get('https://www.akjsbdas,la.zxcvksam')
    if request.status_code == 200:
        print('Web site exists')
except:
    print('Web site does not exist')

or to improve the code, you can specify the exception error and make it even better:

import requests
url= 'testashsbfdckasjd.com'
try:
    get = requests.get(url)
    if get.status_code == 200:
        print(f"{url}: does exists")
    else:
        print(f"{url}: does not exist, status_code: {get.status_code}")

except requests.exceptions.RequestException as ReqExcp:
    raise SystemExit(f"{url}: does not exist nError: {ReqExcp}")
Answered By: DrunkLeen
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.