Python WebScraping CSRF令牌问题

2024-10-01 11:31:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用MechanicalSoup通过python3.6登录到一个网站,CSRF令牌有问题。在

每次我请求返回html时,我都会读到“Invalid CSRF token:Forbidden”。在登录页面上搜索html,与看起来像令牌的元素id最匹配的是“authenticity_token”,它似乎已经被令牌填充了。在

我能够使用“re”模块提取令牌,并使用上面提到的id将其重新提交给元素,但没有运气。注意,我必须通过id找到元素,因为没有为它提供名称(这就是为什么我的Robobrowser方法没有起作用)。在

我认为这是与CSRF相对应的元素:

<input id="authenticity_token" type="hidden" value="b+csp/9zR/a1yfuPPIYJSiR0v8jJUTaJaGqJmJPmLmivSn4GtLgvek0nyPvcJ0aOgeo0coHpl94MuH/r1OK5UA==">

在本例中,我将提取“b+csp/9zR/a1ySupplyJSIR0v8jjutajagqjmjpmlmivsn4gtlgvek0nypcj0aogeo0cohpl94muh/r1OK5UA==”并将其重新提交给该元素

下面是我的代码,其中包含user、pass和url的伪值

^{pr2}$

Tags: 模块retokenid元素网站html页面
1条回答
网友
1楼 · 发布于 2024-10-01 11:31:31

我认为这里的问题是<input>元素必须具有name属性,才能通过POST或GET提交。因为您的令牌在一个name-无<input>元素中,所以它不会被MechanicalSoup处理,因为浏览器会这样做。在

W3C specification

Every successful control has its control name paired with its current value as part of the submitted form data set. A successful control must be defined within a FORM element and must have a control name.

...

A control's "control name" is given by its name attribute.

可能有一些JavaScript正在处理CSRF令牌。在

有关类似的讨论,请参见Does form data still transfer if the input tag has no name?


关于MechanicalSoup的使用,类StatefulBrowser和{}将简化脚本。例如,如果您只需打开页面并输入用户名和密码:

import mechanicalsoup

# These values are filled by the user
url = ""
username = ""
password = ""

# Open the page
browser = mechanicalsoup.StatefulBrowser(raise_on_404=True)
browser.open(url)

# Fill in the form values
form = browser.select_form('form[id=loginForm]')
form['username'] = username
form['password'] = password

# Submit the form and print the resulting page text
response = browser.submit_selected()
print(response.text)

相关问题 更多 >