简体   繁体   中英

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?

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')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM