首页 > 解决方案 > 一直拿不到 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

标签: pythonpython-3.xcookiespython-requestscsrf

解决方案


您没有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)]

推荐阅读