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

时间:2016-10-06 14:46:32

标签: python http urllib2

我正在使用urllib2.urlopen在一段时间(True)循环中调用Python中的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

我每次拨打电话时都会通过更改网址从主函数调用上述方法。

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

response = urlopen(url)

它等待等待......

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

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

我读到了

response = urlopen(url, timeout=10)

但是如果失败会重复通话呢?

2 个答案:

答案 0 :(得分:2)

根据您要尝试的重试次数,在循环中使用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

答案 1 :(得分:1)

使用此方法,您可以重试一次。

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