urllib.request.Request超时参数错误

urllib.request.Request timeout argument error

当我向函数添加超时参数时,我的代码总是进入异常并打印出 "I failed"。当我删除超时参数时,代码会正常工作,并进入 try 子句。关于 urllib.request 函数中超时参数如何工作的任何信息?

import urllib.request
url = 'whosebug.com'

try:
    req = urllib.request.Request("http://" + url, timeout = 1000000000)
    req = urllib.request.urlopen(req)
    print("I tried.")
except:
    print("I failed.")

我尝试使用请求而不是 urllib,代码在包含超时参数的情况下工作。在下面的代码中,它总是进入 try 子句,传递或不传递超时参数。

import requests
url = 'whosebug.com'

try:
    req = requests.get("http://" + url, timeout=1000000)
    print("I tried.")
except:
    print("I failed.")

但是,我不想使用requests,因为稍后我的代码会发生一些冲突。关于如何在 urllib 中包含超时有什么想法吗?

urllib.request.Request no initial parameters such as timeout but it in the urllib.request.urlopen,所以你需要:

import urllib.request
url = 'whosebug.com'

try:
    req = urllib.request.Request("http://" + url)
    req = urllib.request.urlopen(req, timeout=1000000000)
    #                                 ^^^^^^^
    print("I tried.")
except:
    print("I failed.")

如果您查看 Request 函数 (https://docs.python.org/3/library/urllib.request.html#urllib.request.Request) 的文档,您会发现没有超时参数。所以你的函数只是抛出,因为你传递了一个无法识别的关键字参数。查看发生了什么的一种方法是实际捕获并打印异常,如下所示:

import urllib.request
url = 'whosebug.com'

try:
    req = urllib.request.Request("http://" + url,timeout=1000)
    req = urllib.request.urlopen(req)
    print("I tried.")
except Exception as exc:
    print(exc)

打印:

init() 得到了意外的关键字参数 'timeout'