您在混淆标头和有效负载,有效负载 不是JSON编码的 。
这些都是标题:
Host: xyz.website.comAccept: application/json, text/javascript, */*; q=0.01Accept-Language: en-GB,en;q=0.5User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:60.0) Gecko/20100101 Firefox/60.0Referer: http://xyz.website.com/help-me/ZYc5YnContent-Type: application/x-www-form-urlenpred; charset=UTF-8X-Requested-With: XMLHttpRequestContent-Length: 56cookie: csrf_cookie_name=a3f8adecbf11e29c006d9817be96e8d4; ci_session=ba92hlh6o0ns7f20t4bsgjt0uqfdmdtl; _ga=GA1.2.1535910352.1530452604; _gid=GA1.2.1416631165.1530452604; _gat_gtag_UA_21820217_30=1Connection: close
其中大多数是自动化的,不需要手动设置。
requests将
Host根据URL为您设置,
Accept设置为可接受的默认值,
Accept-Language在这种情况下几乎不需要
Referer,除非使用HTTPS,否则出于隐私原因甚至通常不会设置或过滤掉,因此网站不再依赖于设置它,
Content-Type必须实际反映您的内容
POST(而不是JSON!),因此
requests请根据调用方式为您进行设置,
Content-Length必须反映实际内容的长度,因此应按设置
requests的最佳位置进行设置,并
Connection应该绝对由库处理,因为您不想阻止它有效地重用连接。
充其量 您可以设置
X-Requested-With和
User-Agent,但前提是服务器不会接受该请求。该
cookies头反映的cookie浏览器保存的值。您的脚本可以通过使用请求会话对象
GET从
Referer标头(或同一站点上的其他合适的URL)中发起的URL发出初始请求,来从服务器获取其自己的cookie集合,此时服务器应在响应,这些响应将存储在会话中,以在发布请求中重复使用。使用该机制获取您自己的CSRF
Cookie值。
注意
Content-Type标题:
Content-Type: application/x-www-form-urlenpred; charset=UTF-8
当您将字典传递给函数的
data关键字时
requests.post(),该库将为您将数据编码为与该内容类型完全相同的内容。
实际有效载荷是
csrf_test_name=a3f8adecbf11e29c006d9817be96e8d4&vID=9999
这是两个领域,
csrf_test_name以及
vID,那需要你的一部分
payload字典。
请注意,该
csrf_test_name值 与
csrf_cookie_namecookie_中的值 _匹配
。这是网站保护自己免受跨站点伪造攻击的方式,在这种攻击中,第三方可能会代表您尝试发布到相同的URL。这样的第三方将无法访问相同的cookie,因此将被阻止。
您的代码需要获取一个新的cookie ;正确的CSRF实施会限制任何CSRF cookie可以重复使用的时间。
因此 ,至少 需要使其全部工作是:
# *optional*, the site may not care about these. If they *do* care, then# they care about keeping out automated scripts and could in future # raise the stakes and require more 'browser-like' markers. Ask yourself# if you want to anger the site owners and get into an arms race.headers = { 'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:60.0) Gecko/20100101 Firefox/60.0', 'X-Requested-With': 'XMLHttpRequest',}payload = { 'vID': 9999,}url = 'http://xyz.website.com/ajax-load-system'# the URL from the Referer header, but others at the site would probably# also workinitial_url = 'http://xyz.website.com/help-me/ZYc5Yn'with requests.Session() as session: # obtain CSRF cookie initial_response = session.get(initial_url) payload['csrf_test_name'] = session.cookies['csrf_cookie_name'] # Now actually post with the correct CSRF cookie response = session.post(url, headers=headers, data=payload)如果仍然引起问题,则需要尝试另外两个标头,
Accept和
Accept-Language。考虑到这将意味着该站点已经对如何避免自动刮板进行 了
长时间的认真思考。考虑与他们联系,并询问他们是否提供API选项。



