我试图使用Python的请求获取受密码保护的ASP网站的全部内容。
ASP网站的程序员告诉我,使用PowerShell,他可以使用以下脚本获取数据:
$c = $host.UI.PromptForCredential('Your Credentials', 'Enter Credentials','','')
$r = Invoke-WebRequest 'https://server.com/app/login.aspx' -SessionVariable my_session
$form = $r.Forms[0]
$form.fields['xUsername']=$c.UserName
$form.fields['xPassword']=$c.GetNetworkCredential().Password
$r = Invoke-WebRequest -Uri ("https://server.com/app/login.aspx?ReturnUrl=%2Fapp%2FgetData.aspx%3Ftype%3DGETDATA%26id%3D123") -WebSession $my_session -Method POST -Body $form.Fields
我试图使用python的请求库来实现这一点,但似乎无法正常工作。我没有获取数据,而是获得了在没有密码的情况下尝试访问时通常会看到的HTML代码。
import getpass
import requests
requests.packages.urllib3.disable_warnings()
import re
from bs4 import BeautifulSoup
user="my_username"
password=getpass.getpass()
data = {"xUsername":user, "xPassword": password}
with requests.Session() as s:
page = s.get('https://server.com/app/login.aspx',verify=False).content
soup = BeautifulSoup(page)
data["___VIEWSTATE"] = soup.select_one("#__VIEWSTATE")["value"]
data["__VIEWSTATEGENERATOR"] = soup.select_one("#__VIEWSTATEGENERATOR")["value"]
s.post('https://server.com/app/login.aspx', data=data)
open_page = s.post(
"https://server.com/app/login.aspx?ReturnUrl=/app/getData.aspx?type=GETDATA&id=123")
我做错了什么?
答案 0 :(得分:0)
我发现了以下问题:
在“表单数据”下找到的所有数据必须包含在python请求中。再一次,去了Chrome并正常登录网站。 @Chrome:检查>网络>搜索login.asp>在底部我找到了“表单数据”,在我的例子中看起来像这样(在解析的视图上):
__ EVENTTARGET:
__ EVENTARGUMENT:
__ VIEWSTATE:随机长字符串
__ VIEWSTATEGENERATOR:随机十六进制数
__ EVENTVALIDATION:随机长字符串
xUsername:用户
xPassword:密码
btnLogin:登录
所以,正确的python代码如下所示:
tr '\006\015' '<>' < YourFile | grep -Ea '<|>'
我必须以编码形式包含url,否则我将从服务器收到一条错误消息,指出缺少一个参数,即:
import getpass
import requests
requests.packages.urllib3.disable_warnings()
from bs4 import BeautifulSoup
user="my_username"
password=getpass.getpass()
url = "https://server.com/app/login.aspx?ReturnUrl=%2fapp%2fgetData.aspx%3ftype%3dGETDATA%26id%3d123"
data = {"xUsername":user, "xPassword": password}
with requests.Session() as s:
headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36"}
r = s.get('https://server.com/app/login.aspx',verify=False,headers=headers)
soup = BeautifulSoup(r.content)
data["___VIEWSTATE"] = soup.select_one("#__VIEWSTATE")["value"]
data["__VIEWSTATEGENERATOR"] = soup.select_one("#__VIEWSTATEGENERATOR")["value"]
data["__EVENTTARGET"] = ""
data["__EVENTARGUMENT"] = ""
data["__EVENTVALIDATION"] = soup.select_one("#__EVENTVALIDATION")["value"]
data["btnLogin"] = "Login"
response = s.post(url,data=data, headers=headers, allow_redirects=True)
print response.content
也许有人知道更好的方法,不必解码网址。