8.网络爬虫—深入理解Ajax请求与SSL证书验证
import requests
# 发送AJAX请求的示例函数
def send_ajax_request(url, session, headers=None):
try:
response = session.get(url, headers=headers, timeout=5)
if response.status_code == 200:
return response.json()
else:
print(f"请求失败,状态码: {response.status_code}")
except requests.exceptions.RequestException as e:
print(f"请求出错: {e}")
except requests.exceptions.Timeout as e:
print(f"请求超时: {e}")
except requests.exceptions.TooManyRedirects as e:
print(f"重定向过多: {e}")
except requests.exceptions.HTTPError as e:
print(f"HTTP错误: {e}")
except requests.exceptions.ConnectionError as e:
print(f"连接错误: {e}")
except requests.exceptions.SSLError as e:
print(f"SSL错误: {e}")
# 使用示例
url = "https://api.example.com/data"
headers = {"User-Agent": "My User Agent 1.0"}
# 创建一个requests.Session实例
session = requests.Session()
# 发送AJAX请求
send_ajax_request(url, session, headers)
这个代码示例展示了如何使用requests库来发送AJAX请求,并处理可能出现的异常。它创建了一个requests.Session
实例来管理cookie,并且在发送请求时指定了headers。对于出现的异常,它打印出错误信息,这有助于调试和了解发生了什么。
评论已关闭