Reputation: 252
I am trying to execute a JS file through python, selenium but I think I miss something.
I tried to call the checking
variable from safari console, but it shows the following error Can't find the checking variable.
I also tried to execute the following code line driver.execute_script('var checking=0;')
but I got the same result when I tried to call the checking
variable from Safari Console.
PYTHON CODE
driver.execute_script(open("/Users/Paul/Downloads/pythonProject/Social media/javascripts/Initializing Variables.js").read())
JS FILE
var checking;
function Checking(item) {
if (item) {
checking = true;
}
else {
checking = false;
}
}
Any ideas?
Upvotes: 2
Views: 1039
Reputation: 2968
All variables will be available just in single execute_script
command context. So it's not possible to define variable in one driver command and modify it or get by another, unless you put the data to document, localstorage or sessionstorage..
But you're able to declare and put something to the variable, just don't forget to return it's value in script.
If I execute this script with driver.execute_script
var a;
function setAValue(arg) {
a = arg;
}
setAValue(100);
return a;
you'll get 100 in the output result.
And if you want to run your file from script, the file should ends with the function invocation and the return statement.
Share function and variables between scripts
This is working example in groovy language (sorry no python env)
WebDriverManager.chromedriver().setup()
WebDriver driver = new ChromeDriver()
driver.get("https://stackoverflow.com/")
//define variable date and function GetTheDatesOfPosts
driver.executeScript('''
document.date = [];
document.GetTheDatesOfPosts = function (item) { document.date = [item];}
''')
//use them in new script
println (driver.executeScript('''
document.GetTheDatesOfPosts(7);
return document.date;
'''))
driver.quit()
it prints [7]
.
Upvotes: 2
Reputation: 15461
Here's a quick tutorial on local vs globally scoped variables.
If you run a command such as:
self.execute_script("var xyz = 'abc';")
and then go to the console to try to find xyz
, it won't be there (xyz is not defined
).
However, if you run:
self.execute_script("document.xyz = 'abc';")
then it will be in the browser console if you type document.xyz
.
That's the short summary. If you just try to declare a local variable when run from execute_script
, then it'll go out-of-scope after the script is run. However, if you attach a variable to a persistent one, that's one way of keeping the variable around (and still accessible).
Upvotes: 3