[Python] Error when accessing incorrect url in python requests

Discussão em 'Python' iniciado por Stack, Março 16, 2025.

  1. Stack

    Stack Membro Participativo

    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?

    Continue reading...

Compartilhe esta Página