Python请求如何在发布之前调用js函数以计算一些值?
作者:互联网
我使用请求(2.2.1)登录URL http://tx3.netease.com/logging.php?action=login,但是此URL的登录逻辑与Django的csrf令牌机制不同,即:
>当您获取此URL时,html文本中有两个导入值formhash和sts,这两个导入值都将在js函数do_encrypt中使用(在文件http://tx3.netease.com/forumdata/cache/rsa/rsa_min中.js).很好,我可以轻松地通过re抓住它们.
html文本的关键部分是:
<form method="post" name="login" id="loginform" class="s_clear" onsubmit="do_encrypt('ori_password','password');pwdclear = 1;" action="logging.php?action=login&loginsubmit=yes">
<input type="hidden" name="formhash" value="91e54489" />
<input type="hidden" name="referer" value="http://tx3.netease.com/" />
<input type="hidden" name="sts" id="sts" value="1409414053" />
<input type="hidden" name="password" id="password" />
...
<input type="password" id="ori_password" name="ori_password" onfocus="clearpwd()" onkeypress="detectCapsLock(event, this)" size="36" class="txt" tabindex="1" autocomplete="off" />
...
</form>
2.输入电子邮件和原始密码ori_password后,单击Submit按钮将调用do_encrypt,它将使用formhash,sts和ori_password设置post dict的真实密码.问题出来了-似乎没有办法直接获取密码字符串. (相比之下,在Django情况下,您可以直接从session_client.cookies [‘csrftoken’]获取csrfmiddlewaretoken)
这是代码:
import requests
import json
import re
loginUrl = "http://tx3.netease.com/logging.php?action=login"
client = requests.session()
r = client.get(loginUrl)
r.encoding='gb18030'
stsPat = re.compile('<input type="hidden" name="sts" id="sts" value="(\d+?)" />')
formhashPat = re.compile('<input type="hidden" name="formhash" value="([\d\w]+?)" />')
sts = stsPat.search(r.text).groups()[0]
formhash = formhashPat.search(r.text).groups()[0]
loginData={
'username' : "smaller9@163.com",
'password' : ..., # Set by js function do_encrypt
'referer':'/',
'loginfield':'username',
'ori_password':'', # it's `111111`, but `do_encrypt` will set it to empty.
'loginsubmit':'true',
'sts':sts,
'formhash':formhash,
}
# r = client.post(url=loginUrl,data=loginData)
解决方法:
假设您具有这样做的权限,请尝试使用硒登录,因为我认为这将与您最终尝试的操作更加一致.
from selenium import webdriver
USERNAME = "foo@bar.com"
PASSWORD = "superelite"
# create a driver
driver = webdriver.Firefox()
# get the homepage
driver.get("http://tx3.netease.com/logging.php?action=login")
un_elm = driver.find_element_by_id("username")
pw_elm = driver.find_element_by_id("ori_password")
submit = driver.find_element_by_css_selector("[name=loginsubmit]")
un_elm.send_keys(USERNAME)
pw_elm.send_keys(PASSWORD)
# click submit
submit.click()
# get the PHPSESSID cookie as that has your login data, if you want to use
# it elsewhere
# print driver.get_cookies():
# do something else ...
标签:python-requests,python 来源: https://codeday.me/bug/20191029/1958164.html