我有一个简单的函数(在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
看看docs:
您可以为您的流程设置一个实际的
timeout
(以秒为单位):为了让代码停止压缩,请将所有内容移到
^{pr2}$try except
块中:现在,如果发生超时,您将捕获异常,程序将不会崩溃。在
祝你好运:)
首先,有一个timeout参数可以用来控制
urlopen
允许的时间。接下来,urlopen
中的超时应该只抛出一个异常,更确切地说是一个socket.timeout
。如果你不想让它中止程序,你只要抓住它:相关问题 更多 >
编程相关推荐