Requests — how to tell if you're getting a 404

后端 未结 1 1926
刺人心
刺人心 2020-12-12 13:32

I\'m using the Requests library and accessing a website to gather data from it with the following code:

r = requests.get(url)

I want to ad

相关标签:
1条回答
  • 2020-12-12 14:03

    Look at the r.status_code attribute:

    if r.status_code == 404:
        # A 404 was issued.
    

    Demo:

    >>> import requests
    >>> r = requests.get('http://httpbin.org/status/404')
    >>> r.status_code
    404
    

    If you want requests to raise an exception for error codes (4xx or 5xx), call r.raise_for_status():

    >>> r = requests.get('http://httpbin.org/status/404')
    >>> r.raise_for_status()
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "requests/models.py", line 664, in raise_for_status
        raise http_error
    requests.exceptions.HTTPError: 404 Client Error: NOT FOUND
    >>> r = requests.get('http://httpbin.org/status/200')
    >>> r.raise_for_status()
    >>> # no exception raised.
    

    You can also test the response object in a boolean context; if the status code is not an error code (4xx or 5xx), it is considered ‘true’:

    if r:
        # successful response
    

    If you want to be more explicit, use if r.ok:.

    0 讨论(0)
提交回复
热议问题