python 拦截http
时间: 2023-08-26 18:12:51 浏览: 65
您可以使用 Python 中的 requests 库来拦截 HTTP 请求。具体方法是使用 requests 库中的 Session 对象来发送 HTTP 请求,并通过重写 Session 对象的 send 方法来拦截请求和响应。
以下是一个简单的示例代码,演示如何使用 requests 库拦截 HTTP 请求:
```python
import requests
class InterceptSession(requests.Session):
def send(self, request, **kwargs):
print('Intercepted request:', request.url)
response = super().send(request, **kwargs)
print('Intercepted response:', response.status_code)
return response
session = InterceptSession()
response = session.get('https://www.baidu.com/')
print(response.status_code)
```
在上面的代码中,我们定义了一个名为 InterceptSession 的类,该类继承自 requests 库的 Session 类,并重写了 send 方法。在 send 方法中,我们打印了请求的 URL,并调用了父类 Session 对象的 send 方法来发送请求和获取响应。最后,我们又打印了 HTTP 响应的状态码。
在主程序中,我们创建了一个 InterceptSession 对象,并使用它来发送 HTTP GET 请求。通过运行上面的代码,您可以看到请求和响应的详细信息被打印出来,从而实现了拦截 HTTP 请求的效果。