Selenium: Save and Load LocalStorage to/from File

2020-07-28 09:01发布

问题:

I'm currently writing a script in python to tell me how many unread messages I have in WhatsApp. To get the count of unread messages selenium opens web.whatsapp.com however I have to authenticate every time. I found out that WhatsApp saves the data to authenticate in the LocalStorage so I'm trying to figure out how I can save the contents from LocalStorage to a file and then later read from it and set all the keys.

I tried:

localStorage = driver.execute_script('return window.localStorage;')
print(localStorage)

but when I do that my terminal running the script just crashes.

回答1:

Create a new user profile on your browser, activate it and login to web.whatsapp.com using the newly created profile, close the browser. Run the python script and initiate the webdriver using the new profile and you should still be logged in, i.e.:


The example below is for Firefox and web.whatsapp.com, but the general concept can be used on other browsers and websites.

1 - Type about:profiles on the browser url box an press enter
2 - Click Create a New Profile

3 - Choose a name and folder for the new profile (take note of the profile location), in this case : d:\ff_profiles\selenium_user

4 - Activate the new browser profile

5 - Login to any website that you want to skip the login process on selenium, in this case, web.whatsapp.com

6 - Once you've logged in successfully (after scanning the QR code) close the browser

7 - Using the profile on your script

from selenium import webdriver
fp = webdriver.FirefoxProfile('d:\\ff_profiles\\selenium_user') 
driver = webdriver.Firefox(firefox_profile=fp)
driver.get("https://web.whatsapp.com")
# you should still be logged in.