selenium 在我的脚本执行后,我怎样才能返回到当前打开的驱动程序窗口?

14ifxucb  于 2023-01-17  发布在  其他
关注(0)|答案(1)|浏览(142)

我正在使用 selenium webdriver与chrome webdriver。我得到了一个网址的driver.get(" ...")和做一些东西和网页抓取(例如点击一些按钮,获得一些信息和登录到网站)。
当脚本运行并完成时,我想运行另一个脚本来继续上次打开的窗口(因此在这种情况下,我不必花费大量时间登录该站点,点击一些按钮,直到我到达我想要的地方)。例如imagin你想登录到你的gmail帐户,点击一些按钮到达你的邮箱,你的脚本就在这里完成。然后你想运行另一个脚本来逐个打开你的电子邮件。

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

我不想打开一个新的chrome驱动程序并再次逐行运行我的代码。我希望引用当前chrome驱动程序的内容。

xa9qqrwz

xa9qqrwz1#

您需要保存会话Cookie才能返回到以前的状态。您可以通过以下方式进行此操作

# 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': ''})

但是这种解决方案并不十分优雅,您可以使用pickle来存储和加载cookie

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)

相关问题