urllib2.urlopen 超时仅在连接到 Internet 时有效

urllib2.urlopen timeout works only when connected to Internet

我正在编写 Python 2.7 代码,使用 urllib2 库从 HTML 页面读取值。 我想在没有互联网的情况下在 5 秒后超时 urllib2.urlopen 函数并跳转到剩余代码。

当计算机连接到有效的互联网连接时,它可以正常工作。为了测试我是否设置 timeout=0.1 它突然超时而没有打开 url,正如预期的那样。 但是当没有 Internet 时,超时不起作用 我将超时设置为 0.1、5 或任何其他值。它根本不会超时。

这是我的代码:

import urllib2
url = "https://alfahd.witorbit.net/fingerprint.php?n"
try:
    response = urllib2.urlopen(url , timeout=5).read()
    print response 
except Exception as e:
    print e

以超时值 5 连接到 Internet 时的结果:

180

连接到超时值为 0.1 的 Internet 时的结果:

<urlopen error timed out>

似乎超时有效。

NOT 连接到 Internet 且具有任何超时值时的结果(每次打开 url 时大约 40 秒后超时,尽管我设置了任何值timeout=:

<urlopen error [Errno -3] Temporary failure in name resolution>

当没有 Internet 连接时,如何使 urllib2.urlopen 超时?我错过了什么吗?请指导我解决这个问题。谢谢!

因为名称解析发生在发出请求之前,所以它不受超时限制。您可以通过在 /etc/hosts 文件中提供主机的 IP 来防止名称解析中出现此错误。例如,如果主机是 subdomain.example.com 并且 IP 是 10.10.10.10 您将在 /etc/hosts 文件

中添加以下行
10.10.10.10    subdomain.example.com

或者,您可以直接使用 IP 地址,但是,某些网络服务器要求您使用主机名,在这种情况下,您需要修改 hosts 文件以离线使用该名称.