简体   繁体   English

Python Selenium 变量未定义

[英]Python Selenium variable not defined

I have a js file and i want to run it in a webpage.我有一个 js 文件,我想在网页中运行它。 I am defining a lot of variable and function in this js file.我在这个js文件中定义了很多变量和function。 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 .我可以使用execute_script(myScript)运行代码,但是当我这样做时,我不能在之前execute_script中定义的execute_script中使用任何变量或 function 。

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 selenium.common.exceptions.JavascriptException:消息:javascript 错误:未定义 testVar

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.当使用let test_var = 10声明变量时,该变量将在脚本命名空间中定义,并在脚本完成后消失。

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.如果您担心命名空间污染,可以通过将 object 属性添加到文档并将变量存储在此 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)")

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

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