在Python中,处理网页重定向通常是通过使用`requests`库的`allow_redirects`参数来实现的。以下是如何使用`requests`库处理重定向的示例:
```python
import requests
url = 'http://example.com' 需要访问的URL
response = requests.get(url, allow_redirects=True) 允许重定向
if response.history:
print("Request was redirected")
for resp in response.history:
print(resp.status_code, resp.url)
print("Final destination:")
print(response.status_code, response.url)
else:
print("Request was not redirected")
在上面的代码中,`allow_redirects=True`表示请求将会自动跟随重定向。如果请求被重定向,`response.history`将包含重定向过程中的所有响应,你可以遍历这个列表来查看每个重定向步骤的状态码和URL。
如果你需要更精确地控制重定向行为,可以将`allow_redirects`参数设置为`False`,这样请求就不会自动跟随重定向,而是直接返回最终的响应。