使用urllib库时,结果页面不存在时如何重连

When using the urllib library, how to reconnect when the resulting page does not exist

当我使用urllib.request库获取站点内容时,如果站点连接错误或不存在,我会收到以下错误

urllib.error.URLError: <urlopen error [WinError 10060]>

我的代码就是这样

import urllib.request
while True:
response = urllib.request.urlopen('http://192.168.198.129:8080/search.txt')
html = response.read().decode("gb2312")
print(html)

如何让它在失去连接后重新连接,而不是自动退出。

谢谢!

在Python中,处理异常的标准方式是use try statement:

while True:
    try:
        response = urllib.request.urlopen('http://192.168.198.129:8080/search.txt')
        html = response.read().decode("gb2312")
        print(html)
    except URLError as e:
        // code to execute in case of error
        print("That was an error :(")
        print(e)  # should print out more information about the error