如何使用python登录需要服务器在第一次请求时响应会话ID的页面?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22300275/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to use python to login page which requires session id responded by server on first request?
提问by heisenberg
I am writing a script to log in to some webpage. I using request and request.session module for this purpose.On first request with login parameters server responses a session id.How to set that session id for further login to same page.
我正在编写一个脚本来登录某个网页。为此,我使用 request 和 request.session 模块。在第一个带有登录参数的请求中,服务器响应一个会话 ID。如何设置该会话 ID 以进一步登录到同一页面。
url = "some url of login page"
payload = {'username': 'p05989', 'password': '123456'}
with requests.session() as s:
s.post(url1, data=payload)
sessionid = s.cookies.get('SESSIONID')
print(sessionid)
r = requests.get(url,data=payload)
print(r.text)
in above code, server responses sessionid on first request.How to use that sessionid on second request?
在上面的代码中,服务器在第一个请求时响应 sessionid。如何在第二个请求中使用该 sessionid?
采纳答案by Martijn Pieters
You are already using requests.session(); it handles cookies for you, provided you keep using the sessionfor all your requests:
您已经在使用requests.session();它会为您处理 cookie,前提是您继续使用会话来处理您的所有请求:
url = "some url of login page"
payload = {'username': 'p05989', 'password': '123456'}
with requests.session() as s:
# fetch the login page
s.get(url)
# post to the login form
r = s.post(url1, data=payload)
print(r.text)
You probably do first need to use GETto get the session id set before posting to the login form.
GET在发布到登录表单之前,您可能首先需要使用来获取会话 ID 设置。
The SESSIONIDcookie is handled transparently for you.
该SESSIONIDCookie是你透明地处理。
回答by Vijay
import requests
import webbrowser
url = "https://www.invezta.com/investorsignup.aspx"
payload = {'login-email': 'email',
'login-pwd': 'password'}
with requests.session() as s:
# fetch the login page
s.get(url)
url1='https://www.invezta.com/Pdf_creator.aspx?User_ID='
# post to the login form
r = s.post(url1, data=payload)
print(r.text)

