Python urllib2: Reading content body even during HTTPError exception?

前端 未结 3 1600
天命终不由人
天命终不由人 2021-01-31 13:38

I\'m using urllib2 to fetch a a page via HTTP. Sometimes the resource throws a HTTP error 400 (Bad Request) when my request contains an error. However, that response also cont

3条回答
  •  星月不相逢
    2021-01-31 13:39

    You can read the response message from the HTTPError exception.

    Python3 example

    import urllib.request
    
    try:
        request = urllib.request.Request('http://httpstat.us/418', headers={'Accept': 'text/plain', 'User-Agent': ''})
        with urllib.request.urlopen(request) as page:
            print('success: ' + page.read().decode())
    except urllib.error.HTTPError as httpError:
            error = httpError.read().decode()
            print('error: ' + error)
    

提交回复
热议问题