我有一个简单的函数(在 python 3 中)来获取 url 并尝试解析它:如果有错误代码(例如 404),则打印错误代码,或者将缩短的 url 之一解析为其完整 url。我的网址位于 csv 文件的一列中,输出保存在下一列中。当程序遇到服务器需要很长时间才能响应的 url 时,就会出现问题 - 程序就会崩溃。如果服务器花费的时间太长,是否有一种简单的方法可以强制 urllib 打印错误代码。我调查了Timeout on a function call但这看起来有点太复杂了,因为我才刚刚开始。有什么建议吗?
即(COL A) 短网址 (COL 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 :
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).
您可以为您的流程设置实际的超时
(以秒为单位):
conn = urllib.request.urlopen(urlColumnElem, timeout=realistic_timeout_in_seconds)
为了让您的代码停止崩溃,请将所有内容移至 try except
block 内:
import socket
def urlparse(urlColumnElem):
try:
conn = urllib.request.urlopen(
urlColumnElem,
timeout=realistic_timeout_in_seconds
)
redirect=conn.geturl()
#check redirect
if(redirect == urlColumnElem):
#print ("same: ")
#print(redirect)
return (redirect)
else:
#print("Not the same url ")
return(redirect)
except urllib.error.HTTPError as e:
return (e.code)
except urllib.error.URLError as e:
return ('URL_Error')
except socket.timeout as e:
return ('Connection timeout')
现在,如果发生超时,您将捕获异常,并且程序不会崩溃。
祝你好运:)
关于python - 当页面响应时间过长时,urllib 请求失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43652951/