简体   繁体   English

如何使用 Python 中的 selenium 将值永久保存在本地存储中

[英]How to save values permanently in Local storage using selenium in Python

I am trying to save values in Local storage so that I'm able to access them again after I close and reopen a new session with selenium.我正在尝试将值保存在本地存储中,以便在关闭并重新打开带有 selenium 的新 session 后能够再次访问它们。 I'm able to save and access values from the same session but when I close the browser then try to access the stored variable, it shows as null:我能够从同一个 session 保存和访问值,但是当我关闭浏览器然后尝试访问存储的变量时,它显示为 null:

from selenium import webdriver

driver = webdriver.Chrome()
driver.get("https://www.google.com")
driver.execute_script("localStorage.setItem('testkey', 'myValue');")
driver.execute_script("alert (localStorage.getItem('testkey'));")

The alert occurs as expected when I run the above but when I close and reopen the browser and run the above code after commenting out the setItem line, the alert shows null.当我运行上述程序时,警报按预期发生,但是当我关闭并重新打开浏览器并在注释掉setItem行后运行上述代码时,警报显示 null。 How can I get this working, or is there any other way I can persist values that are set from javascript?我怎样才能让它工作,或者有没有其他方法可以保留从 javascript 设置的值?

You are using some javascript code to store the value with driver instance .您正在使用一些 javascript 代码将值与驱动程序实例一起存储。 So once you close/quit the browser.因此,一旦您关闭/退出浏览器。 session get terminated that's why same code won't work in this case with new driver instance. session 被终止,这就是为什么相同的代码在这种情况下对于新的驱动程序实例不起作用的原因。

Use environment in Python to store and access the variable throughout the execution使用 Python 中的环境在整个执行过程中存储和访问变量

driver.execute_script("localStorage.setItem('testkey', 'myValue');")
driver.execute_script("alert (localStorage.getItem('testkey'));")

value = driver.switch_to.alert.text

# Set environment variables
os.environ['keyword'] = value

# get the environment variable
print(os.getenv('keyword'))

import below module:导入以下模块:

import os

Oh actually this is dead simple I finally figured it out.哦,实际上这很简单,我终于想通了。

from selenium import webdriver
import json

driver = webdriver.Chrome()
driver.get("https://www.google.com")
driver.execute_script("localStorage.setItem('testkey', 'myValue');")
myvariable = driver.execute_script("return localStorage.getItem('testkey');")

Then from python you can store the value anywhere you want for easy retrieval next time.然后从 python 您可以将值存储在您想要的任何位置,以便下次轻松检索。

dicti = {'storage':myvariable}
json.dump(dicti, open("stored.json","w"))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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