将CSRF令牌传递给requests.post()

2 投票
1 回答
5101 浏览
提问于 2025-04-18 17:47

我看到这个帖子 - 使用Python Requests传递csrftoken

我一直在研究这个,想让它在Greenhouse上工作。我正在尝试写一个脚本来自动创建用户资料。

我可以用GET请求和cookies获取数据,但我觉得我在处理X-CSRF的时候遇到了问题。我下载了Mozilla的Live HTTP headers插件来获取CSRF令牌,但我不太确定该怎么传递它。

到目前为止,我有的代码是:

csrf = 'some_csrf_token'
cookie = 'some_cookie_id'
data = dict('person_first_name'='Morgan') ## this is submitting my name on the form
url = 'https://app.greenhouse.io/people/new?hiring_plan_id=24047'  ##submission form page
headers = {'Cookie':cookie}

r = requests.post(url, data=data, headers=headers)

你们有什么想法,我该如何构建我的requests.post请求?

1 个回答

0

如果你希望请求能够自动处理 cookies(小甜饼),你需要设置一个会话。

session = requests.session()
logindata = {'authenticity_token': 'whatevertokenis', 
    'user[email]': 'your@loginemail.com', 
    'user[password]': 'yourpassword',
    'user[remember_me]': '0'}    
login = session.post('https://app.greenhouse.io/users/sign_in', data=logindata) #this should log in in, i don't have an account there to test.
data = dict('person_first_name'='Morgan')
url = 'https://app.greenhouse.io/people/new?hiring_plan_id=24047'
r = session.post(url, data=data) #unless you need to set a user agent or referrer address you may not need the header to be added. 

撰写回答