为什么我不能用Python“请求”库填写这个表单?

2024-09-28 22:25:33 发布

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

我想用Python中的requests库填写登录表单。如下所示,字段的名称是usernamepasswordenter image description here

所以我写了下面的脚本:

session = requests.session()
p = session.post("http://192.168.94.1/SubSystem/Portal/Index1/Login/Login2.aspx", {'username':'myUsername','password':'myPassword'})
print 'headers', p.headers
print 'cookies', requests.utils.dict_from_cookiejar(session.cookies)
print 'html',  p.text

问题是,当我运行它时,它会再次返回登录页面!我的程序怎么了?在

更新:

我也尝试将参数作为数据发送,但是没有任何改变。i、 e下面的代码也返回相同的输出:

^{pr2}$

更新2:

我用打嗝服捕捉数据包,以查看差异:

这是我的浏览器发送的数据包:

POST /SubSystem/Portal/Index1/Login/Login2.aspx HTTP/1.1
Host: 192.168.94.1
Proxy-Connection: keep-alive
Content-Length: 134
Cache-Control: max-age=0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Origin: http://192.168.94.1
User-Agent: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.89 Safari/537.36
Content-Type: application/x-www-form-urlencoded
Referer: http://192.168.94.1/SubSystem/Portal/Index1/Login/Login2.aspx
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.8
Cookie: ASP.NET_SessionId=nntwluu5uhrldzuymsv333uc; CURRENT_LANGUAGE_2=fa

__VIEWSTATE=%2FwEPDwUKMTY5ODAzNzY1MmRkpL4TXtJfODqn0yxypIJaOzkl4YUWynT8urN%2BYYXM%2FnY%3D&Command=LOGIN&username=myUsername&password=myPassword

这是第二个Python脚本发送的包:

POST /SubSystem/Portal/Index1/Login/Login2.aspx HTTP/1.1
Host: 192.168.94.1
Content-Length: 31
Accept-Encoding: gzip, deflate
Accept: */*
User-Agent: python-requests/2.4.3 CPython/2.7.0 Windows/7
Connection: keep-alive
Content-Type: application/x-www-form-urlencoded

username=myUsername&password=myPassword

Tags: httpapplicationsessionusernameloginpasswordcontentrequests
2条回答

看起来您首先需要发送一个POST请求,但是从您最近的更新来看,该POST还需要一些cookies可用—还有一个名为“Command”的隐藏字段,需要用值“LOGIN”发送,所以。在

import requests

URL = "http://192.168.94.1/SubSystem/Portal/Index1/Login/Login2.aspx"

# Set up session object so we can store cookies across requests
session = requests.session()
# GET the page to get any initial cookies required for the POST
r = session.get(URL)
# POST to the login form (making sure to add "Command")
r = session.post(URL, data={'Command': 'LOGIN', 'username': 'x', 'password': 'y'})

至于为什么在保存页面时不获取图像,是因为当浏览器加载页面时,它会看到指向资源/样式表/图像的链接,并发出进一步的访问请求,requests所做的只是按原样加载页面的“文本”。有办法做到这一点,但这超出了回答核心问题的范围。在


根据关于的评论,我可以使用这些会话对象进行多次登录吗?有一种方法。。。在

^{pr2}$

支持@EsseTi的答案,使用data=Payload方法获取它们。在

import requests
payload = {'id_login': 'UserName', 'id_password': 'Password'}
url = #Your URL
something = requests.post(url, data=payload)

相关问题 更多 >