python - 处理 urllib2 返回的 badstatusline(line)?

标签 python python-2.7 exception-handling return urllib2

我有一个简单的互联网检查器正在运行,但它偶尔会返回一个我似乎无法处理的错误...

函数如下:

def internet_on():

    try:
        urllib2.urlopen("http://google.co.uk/", timeout = 10)
        return True
    except urllib2.URLError as e:
        return False
    except socket.timeout as e:
        return False

这是错误:

Traceback (most recent call last):
  File "C:/Testscript.py", line 117, in internet_on
    urllib2.urlopen("http://google.co.uk/", timeout = 10)
  File "C:\Python27\lib\urllib2.py", line 127, in urlopen
    return _opener.open(url, data, timeout)
  File "C:\Python27\lib\urllib2.py", line 410, in open
    response = meth(req, response)
  File "C:\Python27\lib\urllib2.py", line 523, in http_response
    'http', request, response, code, msg, hdrs)
  File "C:\Python27\lib\urllib2.py", line 442, in error
    result = self._call_chain(*args)
  File "C:\Python27\lib\urllib2.py", line 382, in _call_chain
    result = func(*args)
  File "C:\Python27\lib\urllib2.py", line 629, in http_error_302
    return self.parent.open(new, timeout=req.timeout)
  File "C:\Python27\lib\urllib2.py", line 404, in open
    response = self._open(req, data)
  File "C:\Python27\lib\urllib2.py", line 422, in _open
    '_open', req)
  File "C:\Python27\lib\urllib2.py", line 382, in _call_chain
    result = func(*args)
  File "C:\Python27\lib\urllib2.py", line 1214, in http_open
    return self.do_open(httplib.HTTPConnection, req)
  File "C:\Python27\lib\urllib2.py", line 1187, in do_open
    r = h.getresponse(buffering=True)
  File "C:\Python27\lib\httplib.py", line 1045, in getresponse
    response.begin()
  File "C:\Python27\lib\httplib.py", line 409, in begin
    version, status, reason = self._read_status()
  File "C:\Python27\lib\httplib.py", line 373, in _read_status
    raise BadStatusLine(line)
BadStatusLine: ''

如何处理此错误以返回 false,我希望 internet_on 函数在连接时返回 true,但如果不是 true,则应返回 false..

最佳答案

import httplib

...


def internet_on():
    try:
        urllib2.urlopen("http://google.co.uk/", timeout = 10)
        return True
    except (IOError, httplib.HTTPException):
        return False

关于python - 处理 urllib2 返回的 badstatusline(line)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17253955/

相关文章:

python - 失败 : No config file 'alembic.ini' found

python - 使用 Python 和 LXML 从数据框创建 XML 文件

python - 由于 tf.keras.preprocessing.text.Tokenizer.texts_to_sequences 上的 np.hstack 导致尺寸(形状)发生变化

python - 执行 f2py fib1.f -m fib2 -h fib1.pyf 时出现以下错误 File "^ SyntaxError : invalid syntax

python - wxPython检查c++部分是否被删除

exception-handling - 如何在 Visual C++ 控制台应用程序中捕获 Control-C 异常?

python - 如何获取 ANSI 终端中光标的位置?

javascript - HTML 变量转换为 python 变量

Python 尝试/除 : Showing the cause of the error after displaying my variables

c# - 无法在托管代码中捕获 native 异常