简体   繁体   English

Python 3 urllib.request.urlopen

[英]Python 3 urllib.request.urlopen

How can I avoid exceptions from urllib.request.urlopen if response.status_code is not 200?如果response.status_code不是 200,如何避免urllib.request.urlopen异常? Now it raise URLError or HTTPError based on request status.现在它根据请求状态引发URLErrorHTTPError

Is there any other way to make request with python3 basic libs?有没有其他方法可以使用 python3 基本库发出请求?

How can I get response headers if status_code != 200 ?如果status_code != 200我如何获得响应头?

Use try except , the below code:使用try except ,以下代码:

from urllib.request import Request, urlopen
from urllib.error import URLError, HTTPError
req = Request("http://www.111cn.net /")
try:
    response = urlopen(req)
except HTTPError as e:
    # do something
    print('Error code: ', e.code)
except URLError as e:
    # do something
    print('Reason: ', e.reason)
else:
    # do something
    print('good!')

The docs state that the exception type, HTTPError , can also be treated as a HTTPResponse . 文档声明异常类型HTTPError也可以被视为HTTPResponse Thus, you can get the response body from an error response as follows:因此,您可以从错误响应中获取响应正文,如下所示:

import urllib.request
import urllib.error

def open_url(request):
  try:
    return urllib.request.urlopen(request)
  except urllib.error.HTTPError as e:
    # "e" can be treated as a http.client.HTTPResponse object
    return e

and then use as follows:然后使用如下:

result = open_url('http://www.stackoverflow.com/404-file-not-found')
print(result.status)           # prints 404
print(result.read())           # prints page contents
print(result.headers.items())  # lists headers

I found a solution from py3 docs我从 py3 文档中找到了解决方案

>>> import http.client
>>> conn = http.client.HTTPConnection("www.python.org")
>>> # Example of an invalid request
>>> conn.request("GET", "/parrot.spam")
>>> r2 = conn.getresponse()
>>> print(r2.status, r2.reason)
404 Not Found
>>> data2 = r2.read()
>>> conn.close()

https://docs.python.org/3/library/http.client.html#examples https://docs.python.org/3/library/http.client.html#examples

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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