如何使用 Python + Selenium WebDriver 保存和加载 cookie

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15058462/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 13:12:50  来源:igfitidea点击:

How to save and load cookies using Python + Selenium WebDriver

pythonseleniumwebdriver

提问by Aaron Hiniker

How can I save all cookies in Python's Selenium WebDriver to a txt-file, then load them later? The documentation doesn't say much of anything about the getCookies function.

如何将 Python 的 Selenium WebDriver 中的所有 cookie 保存到 txt 文件中,然后再加载它们?该文档并没有对 getCookies 函数进行太多说明。

采纳答案by Ali-Akber Saifee

You can save the current cookies as a python object using pickle. For example:

您可以使用 pickle 将当前 cookie 保存为 python 对象。例如:

import pickle
import selenium.webdriver 

driver = selenium.webdriver.Firefox()
driver.get("http://www.google.com")
pickle.dump( driver.get_cookies() , open("cookies.pkl","wb"))

and later to add them back:

然后将它们添加回来:

import pickle
import selenium.webdriver 

driver = selenium.webdriver.Firefox()
driver.get("http://www.google.com")
cookies = pickle.load(open("cookies.pkl", "rb"))
for cookie in cookies:
    driver.add_cookie(cookie)

回答by Exsonic

Remember, you can only a add cookie for the current domain. If you wanna add a cookie for your Google account, do

请记住,您只能为当前域添加 cookie。如果您想为您的 Google 帐户添加 cookie,请执行以下操作

browser.get('http://google.com')
for cookie in cookies:
    browser.add_cookie(cookie)

回答by Eduard Florinescu

When you need cookies from session to session there is another way to do it, use the Chrome options user-data-dir in order to use folders as profiles, I run:

当您需要从会话到会话的 cookie 时,还有另一种方法可以做到这一点,使用 Chrome 选项 user-data-dir 以便将文件夹用作配置文件,我运行:

chrome_options = Options()
chrome_options.add_argument("user-data-dir=selenium") 
driver = webdriver.Chrome(chrome_options=chrome_options)
driver.get("www.google.com")

You can do here the logins that check for human interaction, I do this and then the cookies I need now every-time I start the Webdriver with that folder everything is in there. You can also manually install the Extensions and have them in every session. Secon time I run, all the cookies are there:

您可以在此处执行检查人机交互的登录,我执行此操作,然后每次我使用该文件夹启动 Webdriver 时都需要我现在需要的 cookie,一切都在那里。您还可以手动安装扩展并在每个会话中使用它们。我第二次运行时,所有的 cookie 都在那里:

chrome_options = Options()
chrome_options.add_argument("user-data-dir=selenium") 
driver = webdriver.Chrome(chrome_options=chrome_options)
driver.get("www.google.com") #Now you can see  the cookies, the settings, extensions, etc, and the logins done in the previous session are present here. 

The advantage is you can use multiple folders with different settings and cookies, Extensions without the need to load, unload cookies, install and uninstall Extensions, change settings, change logins via code, and thus no way to have the logic of the program break, etc Also this is faster than havin to do it all by code.

好处是可以使用多个不同设置和cookies的文件夹,扩展程序无需加载、卸载cookies、安装卸载扩展程序、更改设置、通过代码更改登录,从而没有程序中断的逻辑,等等 此外,这比必须通过代码完成所有工作要快。

回答by Roel Van de Paar

Based on answer by @Eduard Florinescu but with newer code and missing import added:

基于@Eduard Florinescu 的回答,但添加了更新的代码和缺少的导入:

$ cat work-auth.py 
#!/usr/bin/python3

# Setup:
# sudo apt-get install chromium-chromedriver
# sudo -H python3 -m pip install selenium

import time
from selenium import webdriver
from selenium.webdriver.chrome.options import Options

chrome_options = Options()
chrome_options.add_argument("--user-data-dir=chrome-data")
driver = webdriver.Chrome('/usr/bin/chromedriver',options=chrome_options)
chrome_options.add_argument("user-data-dir=chrome-data") 
driver.get('https://www.somedomainthatrequireslogin.com')
time.sleep(30)  # Time to enter credentials
driver.quit()

$ cat work.py 
#!/usr/bin/python3

import time
from selenium import webdriver
from selenium.webdriver.chrome.options import Options

chrome_options = Options()
chrome_options.add_argument("--user-data-dir=chrome-data")
driver = webdriver.Chrome('/usr/bin/chromedriver',options=chrome_options)
driver.get('https://www.somedomainthatrequireslogin.com')  # Already authenticated
time.sleep(10)
driver.quit()

回答by battlesteed

my os is Windows 10, and the chrome version is 75.0.3770.100. I have tried the 'user-data-dir' solution, didn't work. try the solution of @ Eric Klien fails too. finally, I make the chrome setting like the picture, it works!but it didn't work on windows server 2012.

我的操作系统是 Windows 10,chrome 版本是 75.0.3770.100。我试过“用户数据目录”解决方案,没有用。尝试@ Eric Klien 的解决方案也失败了。最后,我按照图片进行了 chrome 设置,它有效!但它在 windows server 2012 上不起作用。

setting

环境

enter image description here

在此处输入图片说明

回答by Jagadeeswara Reddy P

Just a slight modification for the code written by @Roel Van de Paar, as all credit goes to him. I am using this in Windows and it is working perfectly, both for setting and adding cookies:

只是对@Roel Van de Paar 编写的代码稍作修改,所有功劳都归功于他。我在 Windows 中使用它,它运行良好,用于设置和添加 cookie:

from selenium import webdriver
from selenium.webdriver.chrome.options import Options

chrome_options = Options()
chrome_options.add_argument("--user-data-dir=chrome-data")
driver = webdriver.Chrome('chromedriver.exe',options=chrome_options)
driver.get('https://web.whatsapp.com')  # Already authenticated
time.sleep(30)

回答by yong you

this is code I used in windows, It works.

这是我在 Windows 中使用的代码,它有效。

 for item in COOKIES.split(';'):
            name,value = item.split('=',1)
            name=name.replace(' ','').replace('\r','').replace('\n','')
            value = value.replace(' ','').replace('\r','').replace('\n','')
            cookie_dict={  
                    'name':name,
                    'value':value,
                    "domain": "",  # google chrome
                    "expires": "",
                    'path': '/',
                    'httpOnly': False,
                    'HostOnly': False,
                    'Secure': False
                    }
            self.driver_.add_cookie(cookie_dict)