运行python脚本从谷歌静态地图图像获取像素点时出错。我从Google maps - how to get building's polygon coordinates from address?获得了python脚本 我使用python2.7来执行脚本 最初,当我运行脚本时,我没有收到任何错误,但在连续运行3-4小时后,我收到以下错误
Traceback (most recent call last):
File "pyscript.py", line 19, in <module>
imgBuildings = io.imread(urlBuildings)
File "/usr/local/lib/python2.7/dist-packages/skimage/io/_io.py", line 60, in i
with file_or_url_context(fname) as fname:
File "/usr/lib/python2.7/contextlib.py", line 17, in __enter__
return self.gen.next()
File "/usr/local/lib/python2.7/dist-packages/skimage/io/util.py", line 29, in
u = urlopen(resource_name)
File "/usr/lib/python2.7/urllib2.py", line 154, in urlopen
return opener.open(url, data, timeout)
File "/usr/lib/python2.7/urllib2.py", line 435, in open
response = meth(req, response)
File "/usr/lib/python2.7/urllib2.py", line 548, in http_response
'http', request, response, code, msg, hdrs)
File "/usr/lib/python2.7/urllib2.py", line 473, in error
return self._call_chain(*args)
File "/usr/lib/python2.7/urllib2.py", line 407, in _call_chain
result = func(*args)
File "/usr/lib/python2.7/urllib2.py", line 556, in http_error_default
raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
urllib2.HTTPError: HTTP Error 403: Forbidden
我是python的新手,我不知道如何修复它?这是某种缓存问题吗? 非常感谢。
答案 0 :(得分:1)
我已经看到了很多这个问题,并且由于间歇性的网络丢失错误。 try / catch异常处理有一个递归技巧,可以避免这种情况发生,即使您的网络停机数小时。
解释:您尝试下载。如果失败,下载将再次尝试递归重试1 / 4,1 / 2,1,2,4,8,......秒后,等待1小时以进行下一次下载。例如,如果您在公司工作,网络可能会在周末停止运行,但您的代码只会轮询1小时(最长),然后在网络修复后再次恢复。
import time
def recursiveBuildingGetter( urlBuildings, waitTime=0.25 ):
try:
imgBuildings = io.imread(urlBuildings)
except:
print "Warning: Failure at time %f secs for %s" % ( waitTime, str(urlBuildings) )
waitTime = waitTime * 2.0
if ( waitTime > 3600.0 ):
waitTime = 3600.0
time.sleep(waitTime)
imgBuildings = recursiveBuildingGetter( urlBuilding, waitTime )
if ( waitTime == 3600.0 ):
waitTime = 0.25
return imgBuildings