python - 随机 "[Errno -2] Name or service not known"错误

标签 python django networking urllib

我正在使用第三方服务填充本地数据库。我有一个网址列表(大约 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/

相关文章:

python - IPv6 中的 RAW 套接字 UDP 多播

python - Mypy:得到 "function",预期 "Callable[..., Any]"

python - 密码保护整个 Django 应用程序

html - 如何将值从 django 模板化 html 传递到 ajax

ruby - EventMachine - 端口正在使用中

java - 当我尝试连接 mysql 数据库时,主机名显示不同?

python - 将不同大小的嵌套 XML 元素提取到 Pandas 中

python - 无法在 Django 应用程序中对用户进行身份验证

JAVA:如何仅在特定时间段内接受输入

python - scipy 中的最小化,找到 N 维标量函数的所有局部最小值的算法