简体   繁体   中英

How to catch http error 404 with urllib3?

What I'm trying to do

I'm requesting a file from an API. If the file does't exist, I get a 404.

What I tried

I'm trying to handle this, using urllib3 .

I found a lot of great, but outdated (~10 years old), documentation how to do this with with urllib and urllib2 .

How does this work in urllib3 ?

All I found in their docs was this

try:
    http.request('GET', 'nx.example.com', retries=False)
except urllib3.exceptions.NewConnectionError:
    print('Connection failed.')

You can simply look at the status code:

import urllib3

http = urllib3.PoolManager()
r = http.request("GET", "httpbin.org/status/404")
if r.status == 404:
    print("404!")

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