如果第一次调用卡住,如何在 urllib2.urlopen 中发送重复请求到 Python?

How to send a repeat request in urllib2.urlopen in Python if the first call is just stuck?

我正在 Python 中使用 urllib2.urlopen 在 while(True) 循环中调用 URL

我的 URL 每次都在变化(因为 URL 的特定参数每次都有变化)。

我的代码如下所示:

def get_url(url):
    '''Get json page data using a specified API url'''
    response = urlopen(url)
    data = str(response.read().decode('utf-8'))
    page = json.loads(data)
    return page

我每次调用时都通过更改 url 从主函数调用上述方法。

我观察到,在调用函数几次后,突然(我不知道为什么),代码卡在了语句

response = urlopen(url)

它只是等待啊等待...

我如何最好地处理这种情况?

我想确保如果它在 10 秒内没有响应,我会再次拨打相同的电话。

我阅读了

response = urlopen(url, timeout=10)

但是如果失败了,重复调用怎么办?

根据您要尝试的重试次数,在循环中使用 try/catch:

while True:
    try:
        response = urlopen(url, timeout=10)
        break
    except:
        # do something with the error
        pass
# do something with response
data = str(response.read().decode('utf-8'))
...  

这将消除所有异常,这可能不是理想的(更多信息在这里:Handling urllib2's timeout? - Python

用这个方法可以重试一次。

def get_url(url, trial=1):
    try:    
        '''Get json page data using a specified API url'''
        response = urlopen(url, timeout=10)
        data = str(response.read().decode('utf-8'))
        page = json.loads(data)
        return page
    except:
        if trial == 1:
            return get_url(url, trial=2)
        else:
            return