In Python, how do I use urllib to see if a website is 404 or 200?

后端 未结 4 414
北荒
北荒 2020-12-02 07:45

How to get the code of the headers through urllib?

4条回答
  •  广开言路
    2020-12-02 08:10

    For Python 3:

    import urllib.request, urllib.error
    
    url = 'http://www.google.com/asdfsf'
    try:
        conn = urllib.request.urlopen(url)
    except urllib.error.HTTPError as e:
        # Return code error (e.g. 404, 501, ...)
        # ...
        print('HTTPError: {}'.format(e.code))
    except urllib.error.URLError as e:
        # Not an HTTP-specific error (e.g. connection refused)
        # ...
        print('URLError: {}'.format(e.reason))
    else:
        # 200
        # ...
        print('good')
    

提交回复
热议问题