How to use python variable in javascript?

I was on a walk looking for a way to access an invisible text field using selenium webdriver. The only way I got it is to use

driver.execute_script("document.getElementById('text_field').value+='XYZ'") 

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

+5
source share
4 answers

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.

+5
source

You need to get a JavaScript string representation of your Python variable value and paste it into your JavaScript command. Fortunately, the Python json module will do this for you.

 from json import dumps driver.execute_script("document.getElementById('text_field').value+=" + dumps(my_python_variable)) 

I would be afraid to simply insert the value in quotation marks, as other answers showed. What if the value already contains quotation marks or special characters that need to be escaped? What if it's not a string? json.dumps will handle all the necessary formatting and escaping for you, appropriate for the type of your variable.

+2
source

If I do nothing, one of the options:

 driver.execute_script("document.getElementById('text_field').value+='{0}'".format(foo)) 
+1
source

If I understand the problem correctly, you are trying to pass var instead of hard-coded XYZ

 driver.execute_script("document.getElementById('text_field').value+='" + var + "'"); 
0
source

Source: https://habr.com/ru/post/1213645/


All Articles