Python 使用 requests.get 请求带 Basic 认证的网站超时处理
使用requests.get请求带基本认证的网站时,可以设置timeout参数来指定超时时间。如果请求超时,将抛出一个requests.exceptions.Timeout异常。
以下是一个示例代码:
import requests
url = 'https://example.com' # 替换为需要请求的网站URL
username = 'username' # 替换为用户名
password = 'password' # 替换为密码
try:
response = requests.get(url, auth=(username, password), timeout=5) # 设置超时时间为5秒
response.raise_for_status() # 如果请求返回的状态码不是200,抛出异常
print('请求成功!')
except requests.exceptions.Timeout:
print('请求超时!')
except requests.exceptions.RequestException as e:
print('请求发生异常:', e)
在上面的代码中,auth参数用于指定基本认证的用户名和密码,timeout参数设置为5秒,即如果请求超过5秒仍未得到响应,就会抛出Timeout异常。如果请求返回的状态码不是200,还会抛出requests.exceptions.HTTPError异常,可以使用response.raise_for_status()来处理该异常。
请根据实际情况替换示例代码中的URL、用户名和密码,并根据需要调整超时时间。
原文地址: https://www.cveoy.top/t/topic/qp3P 著作权归作者所有。请勿转载和采集!