How do I use python variable in a javascript?

I’ve been on a prowl looking for a way to access a non visible text field using selenium’s webdriver. The only way i got it to work is using


However, instead of using XYZ, I want to use python variables.

Best answer

The normal way to pass variables to the JavaScript code you execute through Selenium is to just pass the variables to execute_script:

foo = "something"
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 what is executed is 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. The arguments are serialized automatically by Selenium.

Interpolating with .format or concatenating strings are fragile ways to do it. For instance if you do 'var foo = "' + foo + '"' this will break as soon as your foo variable has a double quote in it (same with 'var foo = "{0}"'.format(foo)). Using json.dumps is going to avoid this and will work in most cases but it does not take care of something like this:

el = driver.find_element(".something")

// Do stuff with el on the Python side.

var el = arguments[0];
// Do something with el on the JavaScript side.

Selenium knows how to convert the Python object it gives you when you find an object to a DOM object on the JavaScript side. json.dumps does not do this.