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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 04:42:38  来源:igfitidea点击:

Python 3 urllib.request.urlopen

pythonexceptionhttprequesturllibpython-3.4

提问by Bogdan Ruzhitskiy

How can I avoid exceptions from urllib.request.urlopenif response.status_codeis not 200? Now it raise URLErroror HTTPErrorbased on request status.

urllib.request.urlopen如果response.status_code不是 200,如何避免异常?现在它提高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

回答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()

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

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

回答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!')