pythonpython-requests

Error when accessing incorrect url in python requests


import requests
url = "http://sdfsdfasdfsfsdf.com"
res = requests.get(url)
if res == 200:
    print("ok")
else:
    print("wrong")

As shown in the code above, I want to print out "wrong" when I access an unusual url. However, the following error occurs.

Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/urllib3/connection.py", line 174, in _new_conn
    conn = connection.create_connection(
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/urllib3/util/connection.py", line 72, in create_connection
    for res in socket.getaddrinfo(host, port, family, socket.SOCK_STREAM):
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/socket.py", line 954, in getaddrinfo
    for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
socket.gaierror: [Errno 8] nodename nor servname provided, or not known

Do you know the solution to this?


Solution

  • It's likely because the hostname can't be resolved

    Alternative could use try except block here

    import requests
    url = "http://sdfsdfasdfsfsdf.com"
    try:
        res = requests.get(url)
        if res.status_code == 200:
            print("ok")
        else:
            print('wrong')
    except:
        print('wrong')