Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
292 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...