Python 和 CloudFlare 问题

问题描述 投票:0回答:3

由于 CloudFlare 的保护,我试图向 https://1stkissmanga.io/ 发出请求时遇到了困难。我准备了 header 和 cookie(我从 Firefox 中读取)但仍然没有成功。奇怪的是,我可以使用 wget 正确获取该网站。这是我不明白的问题 - wget 没有任何 CloudFlare 绕过机制,所以如果它可以从 wget 工作,那么它不应该也可以从 Python 请求工作吗? 当然,使用 wget 我仍然需要提供 cookie 值,否则 wget 也会命中 CloudFlare。 使用 wget(成功结果):

wget "https://1stkissmanga.io/" -U "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:97.0) Gecko/20100101 Firefox/97.0" --header="Cookie: __cf_bm=<some long string with dots and other special characters>"

使用蟒蛇:

headers = {"user-agent": "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:97.0) Gecko/20100101 Firefox/97.0",} cookies = {"__cf_bm": "<some long string with dots and other special characters>",}

url = "https://1stkissmanga.io/" res = requests.get(url, headers=headers, cookies=cookies) 

我也尝试将cookie放入标头中

headers = {"user-agent": "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:97.0) Gecko/20100101 Firefox/97.0", "cookie": "__cf_bm=<some long string with dots and other special characters>",}

并执行

res = requests.get(url, headers=headers)
,但结果是相同的。无论我做什么,请求始终停止 CloudFlare 保护。

不知道下一步该做什么,CloudFlare 代理目前是不可能的。

python cookies python-requests cloudflare
3个回答
0
投票

您应该在“Cookie”键中使用字符串,而不是字典。它应该看起来像这样

{"user-agent": "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:97.0) Gecko/20100101 Firefox/97.0", "Cookie": "cf_clearance=<some hash here>; cf_chl_2=<some hash here>; cf_chl_prog=x11; XSRF-TOKEN=<some hash here>; laravel_session=<some hash here>; __cf_bm=<some hash here>;"}


0
投票

完整的代码如下所示,但请记住检查会持续 10-15 分钟,之后您将需要从浏览器获取新的 cookie。

import requests
h = {
"user-agent": "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:97.0) Gecko/20100101 Firefox/97.0", 
"Cookie": "cf_clearance=<some hash here>; cf_chl_2=<some hash here>; cf_chl_prog=x11; XSRF-TOKEN=<some hash here>; laravel_session=<some hash here>; __cf_bm=<some hash here>;"
}
requests.get(url, headers=h)

0
投票

您的代码的问题是标题的大小写。标头应该不区分大小写,但 cloudflare 希望大小写与所使用的浏览器一致。我发现成功地强制客户端像 wget 那样使用 HTTP 1.1,并像 FF 那样使用标题大小写的标头。

这不起作用:

GET / HTTP/1.1
cookie: __cf_bm=????
accept: */*
accept-encoding: identity
connection: Keep-Alive
user-agent: Mozilla/5.0 (X11; Linux x86_64; rv:109.0) Gecko/20100101  Firefox/119.0
host: ????

这有效:

GET / HTTP/1.1
Cookie: __cf_bm=????
Accept: */*
Accept-Encoding: identity
Connection: Keep-Alive
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:109.0) Gecko/20100101 
Firefox/119.0
Host: ????
© www.soinside.com 2019 - 2024. All rights reserved.