How to get access token from local Storage when using python and selenium webdriver

I using python and selenium to implement automation test for case refresh token with access token store in localStorage. I can log in successfully and when try to print out value from localStorage it has data. However when I try implement to refresh token from API, I cannot get anything from localStorage although it’s saved to localStorage.
Here is my code:

import os
import json
import time
import requests
from dotenv import load_dotenv
from selenium import webdriver
from selenium.webdriver.edge.service import Service as EdgeService
from selenium.webdriver.edge.options import Options as EdgeOptions
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

def login_and_get_access_token():
    # Set up Edge
    options = EdgeOptions()
    options.use_chromium = True

    # Path to Edge WebDriver
    edge_driver_path = os.path.join(os.path.dirname(__file__),  '../../../../driversedge/msedgedriver.exe')
    service = EdgeService(executable_path=edge_driver_path)

    # Initialize Edge browser with Selenium
    driver = webdriver.Edge(service=service, options=options)
.......
# Check data from localStorage
        local_storage_check_script = """
        (function() {
            const key = 'persist:root';
            const item = localStorage.getItem(key);
            console.log('Item retrieved:', item);
            return item;
        })();
        """
        persisted_state = driver.execute_script(local_storage_check_script)
        
        # Print out data for checking
        print("Persisted state:", persisted_state)

        if not persisted_state:
            raise Exception("Failed to retrieve persisted state from localStorage")

        # Convert data from JSON string to dict
        auth_state = persisted_state.get('auth', '{}')
        auth_state_json = json.loads(auth_state)

        access_token = auth_state_json.get('access_token')
        if not access_token:
            raise Exception("Access token not found in persisted state")

        # Save the accessToken to the redux-persist.json file
        with open('redux-persist.json', 'w') as file:
            json.dump({'accessToken': access_token}, file)

        return access_token

When I print out print(“Persisted state:”, persisted_state), it’s has value is None. Maybe I have some mistake but I cannot debugging. How can I get value from localStorage and using it to get accessToken after that call API refresh token from Back End?

Read more here: Source link