python - 一直拿不到 CSRF 令牌
问题描述
我正在尝试在 Spotify 登录页面上获取 csrf 令牌。我以前这样做没问题,但现在我似乎只能得到 50% 的令牌。我尝试了这个简单的代码:
import requests
def Main():
s = requests.session()
s.get("https://accounts.spotify.com/en/login/?_locale=en-US&continue=https:%2F%2Fwww.spotify.com%2Fus%2Faccount%2Foverview%2F")
print(s.cookies)
print(s.cookies.get_dict())
try:
print(s.cookies['csrf_token'])
except KeyError:
Main()
Main()
如果你运行这个程序,你会看到 CSRF 只打印了几次,而其他时间什么也没打印。为什么请求只能有时而不是总是能够获取 CRSF cookie/令牌?我以前从来没有遇到过这个问题。
编辑:我的请求版本是 2.21.0
解决方案
您没有csrf_token
间歇性访问的原因是因为您经常访问网站或者您在没有标题的情况下访问它 --- 服务器认为您可能是机器人或攻击者。这些原因会导致服务器响应 40x 或 50x。所以你应该添加标题并将间隔设置为 1 秒。
import requests
import time
def Main():
time.sleep(1)
with requests.session() as s:
s.headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36",
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
"Accept-Encoding": "gzip, deflate, br"
}
resp = s.get("https://accounts.spotify.com/en/login/?_locale=en-US&continue=https:%2F%2Fwww.spotify.com%2Fus%2Faccount%2Foverview%2F")
print(s.cookies['csrf_token'])
[Main() for _ in range(10)]
推荐阅读
- python - functools 没有属性 lru_cache
- php - Laravel:从 html 表中获取复选框值
- ios - 如何使用 Swifter 库为 twitter 使用 getBlockedUsers
- javascript - 字符串的连接不起作用 - Javascript
- reactjs - React - 表 tr 和 td 点击事件
- arduino - 无法使用 AT+CMGS="XXXXXXXXX" 设置接收方电话号码返回错误 325
- javascript - 使 Fullpage-Scroll-Script 不那么静态
- css - 使用 Razor 未在 asp.net mvc 中加载 CSS 样式表
- c++ - 如何将修改后的 llvm 位码保存到给定的文件名?
- c++ - __m128d 不是原生对齐的吗?