使用Python请求模块向ASP.NET页面发出POST请求

时间:2015-07-01 21:05:14

标签: python asp.net post python-requests

我正在尝试向pwreset.seattleu.edu/change.aspx提交POST请求,以便我可以在命令行上更改我的帐户密码。我认为在阅读了各种其他类似的问题之后我已经正确设置了请求,但是返回的响应是完全相同的页面,我的密码没有被更改。有效的回复应该将我重定向到pwreset.seattleu.edu/change_success.aspx

代码

from bs4 import BeautifulSoup
import requests

pwreset_url = "https://pwreset.seattleu.edu/change.aspx"

headers = {
    'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
    'User-Agent': 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.17 (KHTML, like Gecko)  Chrome/24.0.1312.57 Safari/537.17',
    'Content-Type': 'application/x-www-form-urlencoded',
    'Accept-Encoding': 'gzip,deflate,sdch',
    'Accept-Language': 'en-US,en;q=0.8',
    'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3'
}

session = requests.Session()
session.headers.update(headers)

form_response = session.get(pwreset_url, headers=headers) 
soup = BeautifulSoup(form_response.content)

viewstate = soup.find('input', {'name': "__VIEWSTATE"})['value']
viewstategenerator = soup.find('input', {'name': "__VIEWSTATEGENERATOR"})['value']

item_request_body = {
    'VIEWSTATE': viewstate,
    'VIEWSTATEGENERATOR': viewstategenerator,
    '__VIEWSTATEENCRYPTED': '',
    'Username': 'my_username',
    'OldPassword': 'my_password',
    'NewPassword': 'new_password',
    'ConfirmPassword': 'new_password',
    'DoChg': 'Change Password >>'
}

response = session.post(url=pwreset_url, headers=headers, data=item_request_body)

print(BeautifulSoup(response.content))

我做错了吗?

1 个答案:

答案 0 :(得分:0)

几年来帮助原提问者为时已晚,我找到了这个问题的通用解决方案;使用 requests-ntlm,它是为对这些古怪的 ASP.NET 实例进行身份验证而创建的。

这是一个如何使用它的简单示例

import requests
from requests_ntlm import HttpNtlmAuth
​
username = input("username: ")
password = input("password: ") 

with requests.Session() as session:
    session.auth = HttpNtlmAuth(username, password)
    session.get(url)  # use methods of this object to have your result

考虑使用内置的 getpass.getpass() 获取密码字符串或更安全的方法