简体   繁体   English

使用 python 请求打开多个选项卡同时维护 session cookies

[英]Using python requests to open multiple tabs while maintaining session cookies

I am attempting to use requests to obtain information from a website.我正在尝试使用请求从网站获取信息。 The problem is that this website requires a homepage to open in one tab, while the information you need is open in another.问题是这个网站需要在一个选项卡中打开主页,而您需要的信息在另一个选项卡中打开。 If I close that homepage, the page I need no longer keeps my login session. How could I imitate having two tabs open to prevent this issue.如果我关闭那个主页,我需要的页面不再保留我的登录信息 session。我怎么能模仿打开两个选项卡来防止这个问题。 Example:例子:

session = requests.Session()

payload = {'username':'username_here','password':'password_here'}

webSession = session.post("http://website.com/login", data=payload)
webSession2 = session.get("https://website.com/home/home-page")
webSession3 = session.get("https://website.com/Reports/1234")

webSession returns <Response [200]> webSession返回 <Response [200]>

webSession2 also returns <Response [200]>, implying my login was successful. webSession2也返回<Response [200]>,表示登录成功。

webSession3 returns <Response [401]>, implying I'm no longer logged in. webSession3返回 <Response [401]>,暗示我不再登录。

How can I get webSession3 to return the information I want?如何让 webSession3 返回我想要的信息?

You're already creating a Session object. Use it to get cookies after your first request (probably homepage in your case).您已经创建了一个Session object。在您的第一个请求(可能是您的主页)之后,使用它来获取 cookies。

cookies = session.cookies.get_dict()

Now pass cookies in your subsequent request(s):现在在您的后续请求中传递 cookies:

response = session.post("https://website.com/Reports/1234", cookies=cookies)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM