gpt4 book ai didi

Python httplib2 处理异常

转载 作者:太空狗 更新时间:2023-10-30 00:37:15 26 4
gpt4 key购买 nike

我有这个非常简单的代码来检查网站是运行还是关闭。

import httplib2
h = httplib2.Http()
response, content = h.request("http://www.folksdhhkjd.com")
if response.status == 200:
print "Site is Up"
else:
print "Site is down"

当我输入一个有效的 URL 时,它会正确地打印 Site is Up,因为状态是预期的 200。但是,当我输入一个无效的 URL 时,它不应该打印 Site is down 吗?相反,它会打印类似这样的异常

Traceback (most recent call last):
File "C:\Documents and Settings\kripya\Desktop\1.py", line 3, in <module>
response, content = h.request("http://www.folksdhhkjd.com")
File "C:\Python27\lib\site-packages\httplib2\__init__.py", line 1436, in request
(response, content) = self._request(conn, authority, uri, request_uri, method, body, headers, redirections, cachekey)
File "C:\Python27\lib\site-packages\httplib2\__init__.py", line 1188, in _request
(response, content) = self._conn_request(conn, request_uri, method, body, headers)
File "C:\Python27\lib\site-packages\httplib2\__init__.py", line 1129, in _conn_request
raise ServerNotFoundError("Unable to find the server at %s" % conn.host)
ServerNotFoundError: Unable to find the server at www.folksdhhkjd.com

如何覆盖此异常并打印自定义的“站点已关闭”消息?有什么指导吗?

编辑

还有一个问题...使用有什么区别

h = httplib2.Http('.cache')   

h = httplib2.Http()   

最佳答案

try:
response, content = h.request("http://www.folksdhhkjd.com")
if response.status==200:
print "Site is Up"
except httplib2.ServerNotFoundError:
print "Site is Down"

你的代码的问题是,如果主机没有响应,请求不会返回任何状态代码,所以库会抛出一个错误(我认为这是库本身的一个特点,做某种尝试发出请求之前进行 DNS 解析)。

关于Python httplib2 处理异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6757252/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com