Python请求等待重定向

2024-04-25 08:54:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试访问一个网站,通过几秒钟后重定向来验证我不是机器人。如何让请求模块等待重定向

编辑:看来我没有完全理解这个问题。我喜欢Kirk Strauser的回答,但找不到位置标题

我发现该站点是用Cloudflare管理的。我尝试使用cfscrape,但没有成功,cloudscraper还没有更新这个验证码版本。可能不会在stackexchange上解决


Tags: 模块版本编辑标题站点网站机器人cloudflare
2条回答

在这种情况下,您可以先睡一会儿,然后手动访问下一个位置:

import time

import requests

r = requests.get('http://github.com/', allow_redirects=False)

# Don't fetch the next page too quickly
time.sleep(3)

# Now go to the URL that the previous request would have gone to
# if you hadn't asked requests.get not to.
r = requests.get(r.headers['Location'])

如果需要遵循重定向的300系列响应,则requests模块有一个参数用于配置allow_redirects

https://docs.python-requests.org/en/master/user/quickstart/#redirection-and-history

>>> r = requests.get('http://github.com/', allow_redirects=False)

>>> r.status_code
301

>>> r.history
[]

相关问题 更多 >