使用python请求获取CSRF令牌 [英] Get CSRF token using python requests

查看:516
本文介绍了使用python请求获取CSRF令牌的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我当前正在使用Python请求,并且需要CSRF令牌才能登录到站点。根据我的理解,requests.Session()获取cookie,但是显然我需要令牌。而且我也想知道在我的代码中放置它的位置。
导入请求

I am currently using Python Requests, and need a CSRF token for logging in to a site. from my understanding requests.Session() gets the cookie, but obviously I need the token. And Also I would like to know where to place it in my code. import requests

user_name = input('Username:')
payload = {
'username': 'user_name',
'password': 'randompass123'
}


with requests.Session() as s:
p = s.post('https://examplenotarealpage.com', data=payload)


推荐答案

请参见以下代码示例。您可以直接使用它登录仅使用cookie来存储登录信息的网站。

See the following code example. You can use it directly to login into a website that only uses cookies to store login information.

import requests

LOGIN_URL = 'https://examplenotarealpage.com'
headers = {
    'accept': 'text/html,application/xhtml+xml,application/xml',
    'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36'
}

response = requests.get(LOGIN_URL, headers=headers, verify=False)

headers['cookie'] = '; '.join([x.name + '=' + x.value for x in response.cookies])
headers['content-type'] = 'application/x-www-form-urlencoded'
payload = {
    'username': 'user_name',
    'password': 'randompass123'
}

response = requests.post(LOGIN_URL, data=payload, headers=headers, verify=False)
headers['cookie'] = '; '.join([x.name + '=' + x.value for x in response.cookies])

CSRF 令牌有一些可能的位置。不同的网站使用不同的方式将其传递给浏览器。以下是其中一些:

There are a few possible locations of the CSRF token. Different websites use different ways to pass it to browser. Here are some of them:


  • 它可以带有响应标头,在这种情况下,获得它很容易。

  • 有时,页面meta包含CSRF令牌。您必须解析页面的html内容才能获取它。找到合适的CSS选择器。查看示例:

  • It can come with response headers, in that case getting it is easy.
  • Sometimes page meta holds the CSRF token. You have to parse the html content of the page to get it. Find the proper CSS selector for it. See an example:

from bs4 import BeautifulSoup
soup = BeautifulSoup(response.text, 'lxml')
csrf_token = soup.select_one('meta[name="csrf-token"]')['content']


  • 它可以在带有JavaScript代码的脚本标签内。得到它会很棘手。但是,您始终可以使用 regex 隔离它。

    这篇关于使用python请求获取CSRF令牌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆