Python 3 urllib.request.urlopen
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29537298/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python 3 urllib.request.urlopen
提问by Bogdan Ruzhitskiy
How can I avoid exceptions from urllib.request.urlopen
if response.status_code
is not 200? Now it raise URLError
or HTTPError
based on request status.
urllib.request.urlopen
如果response.status_code
不是 200,如何避免异常?现在它提高URLError
或HTTPError
基于请求状态。
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
?
回答by Bogdan Ruzhitskiy
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()
回答by thinkerou
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!')