简体   繁体   中英

Python Selenium variable not defined

I have a js file and i want to run it in a webpage. I am defining a lot of variable and function in this js file. I can run the code with execute_script(myScript) but when i do this, i can't use any variable or function in execute_script that defined in previous execute_script .

This is a test code:

from selenium import webdriver

driver = webdriver.Chrome()

driver.get("https://www.google.com")
driver.execute_script("let testVar = 10")
driver.execute_script("console.log(testVar)")

And this is the error:

selenium.common.exceptions.JavascriptException: Message: javascript error: testVar is not defined

When declaring a variable with let test_var = 10 the variable will be defined in the script namespace and disappear when the script is finished.

If you want to keep the variable for use by another script, you have to anchor it to the document namespace. You can achieve that by defining an attribute on the document instance for example. If you are worried of namespace pollution, you can define a namespace for your scripts by adding an object attribute to document and storing your variables in this object.

from selenium import webdriver

driver = webdriver.Chrome()

driver.get("https://www.google.com")
driver.execute_script("document.testVar = 10")
driver.execute_script("console.log(document.testVar)")

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