How to save and load cookies using Python + Selenium WebDriver

后端 未结 6 626
孤街浪徒
孤街浪徒 2020-11-22 07:52

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

6条回答
  •  一生所求
    2020-11-22 08:22

    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:

    #you need to: from selenium.webdriver.chrome.options import Options
    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:

    #you need to: from selenium.webdriver.chrome.options import Options    
    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.

提交回复
热议问题