代码之家  ›  专栏  ›  技术社区  ›  Tehseen

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

  •  0
  • Tehseen  · 技术社区  · 8 年前

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

    它起作用了 当计算机连接到工作的internet连接时,如预期的那样。如果我设置 timeout=0.1 正如预期的那样,它在没有打开url的情况下突然超时。 但当没有互联网时,超时不起作用 我将timeout设置为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>
    

    似乎超时正在工作。

    结果时间 不是 连接到Internet并具有任何超时值(无论我设置了什么值,每次打开url都会在大约40秒后超时 timeout= :

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

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

    1 回复  |  直到 8 年前
        1
  •  0
  •   sytech    8 年前

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

    10.10.10.10    subdomain.example.com
    

    或者,您可以直接使用IP地址,但是,有些Web服务器要求您使用主机名,在这种情况下,您需要修改 hosts 文件以脱机使用该名称。

    推荐文章