Escape character removed when using selenium execute_script through python

时光毁灭记忆、已成空白 提交于 2021-02-13 17:39:21

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/30745056/escape-character-removed-when-using-selenium-execute-script-through-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!