The usual way to pass variables into JavaScript code executed through Selenium is to simply pass the variables to execute_script :
foo = "something" driver.execute_script(""" var foo = arguments[0]; document.getElementById('text_field').value += foo; """, foo)
You retrieve the argument on the JavaScript side through the arguments object. You can do this because the code you pass to execute_script is wrapped in a function, so something like:
function () { var foo = arguments[0]; document.getElementById('text_field').value += foo; }
and the function is called with the arguments that were passed to execute_script . Arguments are serialized automatically by Selenium.
Interpolation using .format or string concatenation are fragile ways to do this. For example, if you execute 'var foo = "' + foo + '"' , it will break as soon as your variable foo has a double quote (the same with 'var foo = "{0}"'.format(foo) ) Using json.dumps will avoid this and will work in most cases, but it does not care about something like this:
el = driver.find_element(".something") // Do stuff with el on the Python side. driver.execute_script(""" var el = arguments[0]; // Do something with el on the JavaScript side. """)
Selenium knows how to transform the Python object that it gives you when you find the object for the DOM object from the JavaScript side. json.dumps does not do this.
Louis source share