Rick
Rick

Reputation: 3

Escape character removed when using selenium execute_script through python

I need to have these characters in my string: "'\;

userID = "__\"__\'__\;__"

I am running javascript through python to update the username field:

driver.execute_script("window.document.getElementById('username').value = '%s';" %userID)

Now my problem is that in the end my script becomes:

window.document.getElementById('username').value = '__"__'__\;__';

And this causes errors since I have single quote without escape character. How can I keep the escape character in front of the single quote?

Upvotes: 0

Views: 1366

Answers (1)

Louis
Louis

Reputation: 151380

Don't use interpolation. Instead, pass the value as a parameter to execute_script:

driver.execute_script("window.document.getElementById('username').value = arguments[0];", 
                       userID)

The arguments you pass to execute_script after the script are available as arguments[0], arguments[1], etc. on the JavaScript side. (This is not a special Selenium thing but how JavaScript works. The script you give to execute_script is wrapped in a function object and function parameters are available on the arguments object.)

When you pass the value as a parameter like above, Selenium will serialize the Python value to its corresponding JavaScript value on the browser side and it will preserve your string.

Upvotes: 1

Related Questions