Search code examples
pythonseleniumselenium-webdriverselenium-chromedriverwebdriver

how can I return to the window of the driver that is currently opened after my script is executed?


I am using selenium webdriver with chrome webdriver. In script1 I get a URL from the driver.get(" ...") and do some stuff and web scraping( for example clicking some buttoms, getting some informations and loging into the site).

When my script runs and finishes, I want to run another script(script2) that continues the last opened window( so in that case I don't have to spend a lot of time login to that site, clicking some buttons until I reach where I want to be). for example imagine you want to login to your Gmail account and click some buttons to reach your mailbox and your script finishes right here. and then you want to run another script to open your emails one by one.

# script1
driver = webdriver.Chrome() 
driver.get("https://gmail.google.com/inbox/")

inbox_button = driver.find_element_by_xpath("//*[@id=":5a"]/div/div[2]/span/a']")
inbox_button.click()
# the code finishes successfully right here
    # script2
from script1 import driver

emails = driver.find_elements_by_xpath("path to emails']").find_element_by_tag_name("button")
print('email_button: ', emails)

for email in emails

    emails.click()

I do not want to open a new chrome driver and run my code line by line again. I expect something that refers to the current chrome driver.


Solution

  • You need to save your session cookies to be able to return to the previous state. You can either do this by

    # Manually login to the website and then print the cookie
    time.sleep(60)
    print(driver.get_cookies())
    
    # Then add_cookie() to add the cookie
    driver.add_cookie({'domain': ''})
    

    But this solution is not very elegant. You can instead use pickle to store and load the cookies

    1. You would need to install pickle using pip - https://pypi.org/project/pickle5/
    
    2. Add cookies after logging in to gmail
    
          pickle.dump(driver.get_cookies(),open("cookies.pkl","wb"))
    
    3. In the last part, you need to load the cookies and add it to your driver again when opening the browser for the second test
    
         cookies = pickle.load(open("cookies.pkl","rb"))
         for cookie in cookies:
             driver.add_cookies(cookie)