简体   繁体   中英

How to save the session of Whatsapp web with Selenium Python?

My expectation was something would get added to the cookeies array automatically after validation but that isn't the case.

driver = webdriver.Chrome(chromedriver)
whatsapp_url = "https://web.whatsapp.com"
driver.get(whatsapp_url)
print(driver.get_cookies())
time.sleep(30) # We are doing the manual QR code verification here
print(driver.get_cookies())

driver.get_cookies() is empty before and after as well

Try this:

options = webdriver.ChromeOptions();
options.add_argument('--user-data-dir=./User_Data')
driver = webdriver.Chrome(chrome_options=options)
driver.get('https://web.whatsapp.com/')

You need to login first time. It'll work always when you have to store your session. No need to import/export cookies.

I couldn't comment Abhi Bhalgami answer but I need to made some changes based on another post:

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

chromepath = r'E:\chromedriver\chromedriver.exe'
options = webdriver.ChromeOptions() 
options.add_argument("user-data-dir=C:\\Users\\user\\AppData\\Local\\Google\\Chrome\\User Data")
driver = webdriver.Chrome(executable_path=chromepath, chrome_options=options)

extract and save whatsapp session from chrome browser local storage and then use it on another device

am not sure but You can save your current cookies using pickle, For example:

import pickle
from selenium import webdriver

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

after that add them back using this code:

import pickle
from selenium import webdriver

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

Web Whatsapp stores sessions in IndexedDB and sync those values to local storage.

Here is the working code you can try: tithiwa/session.py by using this javascript code

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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