python遇到远程主机强迫关闭了一个现有的连接的问题怎么解决?
使用requests做一个自动检测网站可访问性的小工具遇到“远程主机强迫关闭了一个现有的连接”的问题,然后整个程序中断了
回答:
写个while True和try,将你的语句放到try里面如果发生了错误就间隔3秒,这样就会一直运行了!
回答:
给你两个现成的代码用于解决这个问题(这两段代码来自网络,并非本人原创)
1.用于重试捕获异常
import requestsfrom requests.exceptions import RequestException
url = 'https://example.com' # 要访问的网站
def check_website_access(url, max_retries=3):
retries = 0
while retries < max_retries:
try:
response = requests.get(url)
if response.status_code == 200:
print(f"{url} is accessible")
break
except RequestException as e:
print(f"Failed to access {url}, retrying...")
retries += 1
continue
else:
print(f"Failed to access {url} after {max_retries} retries")
check_website_access(url)
2.用于设置超时时间:
import requestsfrom requests.exceptions import RequestException
url = 'https://example.com' # 要访问的网站
try:
response = requests.get(url, timeout=5)
if response.status_code == 200:
print(f"{url} is accessible")
else:
print(f"Failed to access {url}, status code: {response.status_code}")
except RequestException as e:
print(f"Failed to access {url}: {e}")
这样你可以在类似错误的时候,通过重试或设置超时时间找出大概问题,来处理这类异常了。
以上是 python遇到远程主机强迫关闭了一个现有的连接的问题怎么解决? 的全部内容, 来源链接: utcz.com/p/938938.html