查看该页面的源代码,您可以看到表单具有以下结构:
<form name="form1" method="post" action="login.aspx" id="form1">
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUKMTM0MDY0ODA1OQ8WAh4LVXJsUmVmZXJyZXIFVGh0dHA6Ly9zdGFja292ZXJmbG93LmNvbS9xdWVzdGlvbnMvMTYxMjk0MzEvbG9naW4tdG8tYS1zcGVjaWZpYy13ZWJzaXRlLXVzaW5nLXB5dGhvbhYCAgEPFgIeBFRleHQF7gE8c2NyaXB0IHNyYz0iaHR0cDovL3d3dy5nb29nbGUtYW5hbHl0aWNzLmNvbS9nYS5qcyIgdHlwZT0idGV4dC9qYXZhc2NyaXB0Ij48L3NjcmlwdD48c2NyaXB0IHR5cGU9InRleHQvamF2YXNjcmlwdCI+dHJ5IHt2YXIgcHQgPSBfZ2F0Ll9nZXRUcmFja2VyKCJVQS0zNjM1NjY0LTEiKTtwdC5fc2V0RG9tYWluTmFtZSgnLnBwZGFpLmNvbScpO3B0Ll90cmFja1BhZ2V2aWV3KCk7fSBjYXRjaChlcnIpIHt9PC9zY3JpcHQ+ZBgBBR5fX0NvbnRyb2xzUmVxdWlyZVBvc3RCYWNrS2V5X18WAQUIYnRuTG9naW7FDjuchG1Ou3OnbNrC9L5mLwpESA==" />
<input type="hidden" name="__EVENTVALIDATION" value="/wEWBQLh9ro4AqXVsrMJArWptJELAoLch4YMApCjwqsN3xZOGR6YaITqg9kNkVxXG+bnVLo=" />
<input name="txtUserName" type="text" >
<input name="txtPassword" type="password" />
<input type="image" name="btnLogin" id="btnLogin" />
<input type="hidden" name="HiddenField1" id="HiddenField1" value="http://stackoverflow.com/questions/16129431/login-to-a-specific-website-using-python" />
</form>
因此,您应该能够使用以下数据对http://www.ppdai.com/login.aspx进行 POST
r = requests.post('http://www.ppdai.com/login.aspx', data={
'__VIEWSTATE': '/wEPDwUKMTM0MDY0ODA1OQ8WAh4LVXJsUmVmZXJyZXIFVGh0dHA6Ly9zdGFja292ZXJmbG93LmNvbS9xdWVzdGlvbnMvMTYxMjk0MzEvbG9naW4tdG8tYS1zcGVjaWZpYy13ZWJzaXRlLXVzaW5nLXB5dGhvbhYCAgEPFgIeBFRleHQF7gE8c2NyaXB0IHNyYz0iaHR0cDovL3d3dy5nb29nbGUtYW5hbHl0aWNzLmNvbS9nYS5qcyIgdHlwZT0idGV4dC9qYXZhc2NyaXB0Ij48L3NjcmlwdD48c2NyaXB0IHR5cGU9InRleHQvamF2YXNjcmlwdCI+dHJ5IHt2YXIgcHQgPSBfZ2F0Ll9nZXRUcmFja2VyKCJVQS0zNjM1NjY0LTEiKTtwdC5fc2V0RG9tYWluTmFtZSgnLnBwZGFpLmNvbScpO3B0Ll90cmFja1BhZ2V2aWV3KCk7fSBjYXRjaChlcnIpIHt9PC9zY3JpcHQ+ZBgBBR5fX0NvbnRyb2xzUmVxdWlyZVBvc3RCYWNrS2V5X18WAQUIYnRuTG9naW7FDjuchG1Ou3OnbNrC9L5mLwpESA==',
'__EVENTVALIDATION': '/wEWBQLh9ro4AqXVsrMJArWptJELAoLch4YMApCjwqsN3xZOGR6YaITqg9kNkVxXG+bnVLo='
'txtUserName': 'zhonghao007',
'txtPassword': 'zonghao0915',
'HiddenField1': 'http://www.somereferring-url.com'
}
)
viewstate 和 eventvalidation 看起来像是在每个页面请求中生成的,并且可能用于某种 CSRF 验证。因此,您可能需要首先请求页面,找到这些字段的值,然后使用新生成的字段发出 POST 请求。您还需要确保您正在传递会话 cookie。
或者,您可以使用 Selenium webdriver 直接驱动真正的浏览器。这意味着它肯定会起作用。