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

Categories

0 votes
293 views
in Technique[技术] by (71.8m points)

javascript - 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?

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...