当页面响应时间过长时,urllib请求失败

2024-09-30 14:21:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个简单的函数(在python3中)来获取一个url并尝试解析它:如果有错误代码,则打印一个错误代码(例如404),或者将其中一个缩短的url解析为它的完整url。我的url在csv文件的一列中,输出保存在下一列中。当程序遇到一个url,服务器需要很长时间才能响应时,问题就出现了——程序只是崩溃了。如果服务器花费的时间太长,有没有一种简单的方法可以强制urllib打印错误代码。我研究了Timeout on a function call,但这看起来有点太复杂了,因为我刚刚开始。有什么建议吗?在

即(A列)短URL(B列)http://deals.ebay.com/500276625

def urlparse(urlColumnElem):
    try:
        conn = urllib.request.urlopen(urlColumnElem)
    except urllib.error.HTTPError as e:
        return (e.code)
    except urllib.error.URLError as e:
        return ('URL_Error')
    else:
        redirect=conn.geturl()
        #check redirect
        if(redirect == urlColumnElem):
            #print ("same: ")
            #print(redirect)
            return (redirect)
        else:
            #print("Not the same url ")
            return(redirect)

编辑:如果有人得到http.client.disconnected错误(和我一样),请看这个问题/答案http.client.RemoteDisconnected error while reading/parsing a list of URL's


Tags: 程序服务器httpurlreturnaserrorurllib
2条回答

看看docs

urllib.request.urlopen(url, data=None[, timeout])

The optional timeout parameter specifies a timeout in seconds for blocking operations like the connection attempt (if not specified, the global default timeout setting will be used).

您可以为您的流程设置一个实际的timeout(以秒为单位):

conn = urllib.request.urlopen(urlColumnElem, timeout=realistic_timeout_in_seconds)

为了让代码停止压缩,请将所有内容移到try except块中:

^{pr2}$

现在,如果发生超时,您将捕获异常,程序将不会崩溃。在

祝你好运:)

首先,有一个timeout参数可以用来控制urlopen允许的时间。接下来,urlopen中的超时应该只抛出一个异常,更确切地说是一个socket.timeout。如果你不想让它中止程序,你只要抓住它:

def urlparse(urlColumnElem, timeout=5):   # allow 5 seconds by default
    try:
        conn = urllib.request.urlopen(urlColumnElem, timeout = timeout)
    except urllib.error.HTTPError as e:
        return (e.code)
    except urllib.error.URLError as e:
        return ('URL_Error')
    except socket.timeout:
        return ('Timeout')
    else:
        ...

相关问题 更多 >