首页 > Python urllib urlopen超时之后怎么重置连接?

Python urllib urlopen超时之后怎么重置连接?


    def fetchFrom(self, url):
        try:
            f = urllib.request.urlopen(url=url,timeout=200)
        except urllib.error.URLError as error:
            print(error)
        except urllib.error.HTTPError as error:
            print(error)
            continue
        else:
            print('Got it!')
    

如上,如果我设置了continue,那么超时之后怎么重置这项连接。
因为想要处理有时候访问这个网站可能一下子,刷新一下一下就打开了的情况。

递归有没有什么不妥?

def fetchFrom(self, url):
        try:
            f = urllib.request.urlopen(url=url,timeout=200)
        except urllib.error.URLError as error:
            print(error)
        except urllib.error.HTTPError as error:
            print(error)
            fetchFrom(url)
        else:
            print('Got it!')
            

报错:local variable 'f' referenced before assignment

该怎么写呢?设置成全局变量?


你这个retry,万一真的连接有问题,就会无限循环了。f设成全局变量可以,但是就比较丑陋了

可以考虑用这个装饰器Retry,不要去递归retry

【热门文章】
【热门文章】