【发布时间】:2011-10-09 02:13:13
【问题描述】:
我有这个非常简单的代码来检查一个站点是启动还是关闭。
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 时,它不应该打印站点已关闭吗?相反,它会打印一个类似这样的异常
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()
【问题讨论】: