简体   繁体   English

使用 Python Selenium 在新浏览器中保持登录(保存会话)

[英]Stay logged in(save session) in new browser with Python Selenium

So, I am trying to:所以,我试图:

  1. Open browser打开浏览器
  2. Log-In to website登录网站
  3. Save session/cookies保存会话/cookies
  4. Close browser关闭浏览器
  5. Open new browser打开新浏览器
  6. Load session/cookies and get logged in加载会话/cookies 并登录

I am trying to do this for hours, and it looks like old code from the internet doesn't work.我试图这样做几个小时,看起来互联网上的旧代码不起作用。

Code example:代码示例:

import pickle
from webdriver_manager.chrome import ChromeDriverManager
from selenium import webdriver

# I am using website ascension.gg to test it, as it is very simple
browser = webdriver.Chrome(ChromeDriverManager().install()) 
browser.get('https://ascension.gg/')
time.sleep(20) # during this time, I log in manually
pickle.dump(browser.get_cookies() , open("asc2.pkl","wb")) # save cookies/session ideally
browser.quit()
browser = webdriver.Chrome(ChromeDriverManager().install()) 
browser.get('https://ascension.gg/')
for cookie in pickle.load(open("asc2.pkl", "rb")):
    browser.add_cookie(cookie) # load cookies and restore session
browser.refresh() # logged in back ( doesn't work )

Any help?有什么帮助吗? Why this doesn't work?为什么这不起作用? Thank you in advance.先感谢您。

How about using the chrome profile , which internally handles cookies.如何使用内部处理 cookies 的chrome profile

ChromeOptions options = new ChromeOptions();
# location for a chrome profile creation/access
options.AddArguments(@"user-data-dir=/home/your_id/CHROME_STORAGE");
ChromeDriver driver = new ChromeDriver(options);

This code creates a save location for a profile (including a space for cookies).此代码为配置文件创建一个保存位置(包括 cookie 的空间)。 You do not need to write any manual codes for handling cookies with the above code.您无需编写任何手动代码即可使用上述代码处理 cookies。 Instead, Chrome will handle cookies.相反,Chrome 将处理 cookies。

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

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