通过python使用Selenium execute_script时删除了转义字符 [英] Escape character removed when using selenium execute_script through python

查看:79
本文介绍了通过python使用Selenium execute_script时删除了转义字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在字符串中包含以下字符:'\;

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

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

我正在通过python运行javascript以更新用户名字段:

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?

推荐答案

不要使用插值.而是将值作为参数传递给 execute_script :

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)

您在脚本后传递给 execute_script 的参数可以在服务器上以 arguments [0] arguments [1] 等使用.JavaScript方面.(这不是Selenium的特殊功能,而是JavaScript的工作方式.您提供给 execute_script 的脚本被包装在一个函数对象中,并且

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.)

当您像上面那样将值作为参数传递时,Selenium将在浏览器端将Python值序列化为其相应的JavaScript值,并将保留您的字符串.

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.

这篇关于通过python使用Selenium execute_script时删除了转义字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆