我正在使用第三方服务填充本地数据库。我有一个网址列表(大约 500 个)。我在一个循环中调用每个 url,并用返回的数据更新我的数据库。代码流如下所示:
for url in urllist:
req = urllib.urlopen(url)
data = json.loads(req.read())
req.close()
#update the db using data here
每当我运行这段代码时,脚本都会随机失败并显示错误消息“名称或服务未知”。这与 url 没有任何关系,因为脚本在随机点失败(即一次运行第 50 次迭代,另一次运行第 60 次迭代)
这可能是什么原因?
最佳答案
如果您使用了错误的代理或存在网络问题,您可以试试这个:
for url in urllist:
retry = 0
while True: # retry request
try:
req = urllib.urlopen(url)
resp_data = req.read() # in call read() network still processing
except Exception as e: # TODO need more detailed handling
if retry > 3: # 3 this is serious problem. exit
raise e
retry += 1 # retry
else:
data = json.loads()
req.close() # not needed
break
关于python - 随机 "[Errno -2] Name or service not known"错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20264953/