如何在JavaScript中使用python变量? [英] How do I use python variable in a javascript?
问题描述
我一直在寻找一种使用selenium的webdriver访问不可见文本字段的方法.我让它正常工作的唯一方法是使用
I've been on a prowl looking for a way to access a non visible text field using selenium's webdriver. The only way i got it to work is using
driver.execute_script("document.getElementById('text_field').value+='XYZ'")
但是,我不想使用 XYZ
,而是要使用python变量.
However, instead of using XYZ
, I want to use python variables.
推荐答案
将变量传递给通过Selenium执行的JavaScript代码的正常方法是将变量传递给 execute_script
:
The normal way to pass variables to the JavaScript code you execute through Selenium is to just pass the variables to execute_script
:
foo = "something"
driver.execute_script("""
var foo = arguments[0];
document.getElementById('text_field').value += foo;
""", foo)
您可以通过在JavaScript端检索参数. arguments
object .您可以执行此操作,因为传递给 execute_script
的代码被包装在一个函数中,因此执行的内容类似于:
You retrieve the argument on the JavaScript side through the arguments
object. You can do this because the code you pass to execute_script
is wrapped in a function so what is executed is something like:
function () {
var foo = arguments[0];
document.getElementById('text_field').value += foo;
}
,然后使用传递给 execute_script
的参数来调用该函数.这些参数由Selenium自动序列化.
and the function is called with the arguments that were passed to execute_script
. The arguments are serialized automatically by Selenium.
使用 .format
进行插值或连接字符串是执行此操作的脆弱方法.例如,如果您执行'var foo ='+ foo +'"'
,则只要您的 foo
变量中带有双引号(与'var foo ="{0}"'.format(foo)
).使用 json.dumps
可以避免这种情况,并且在大多数情况下都可以使用,但是并不能解决以下问题:
Interpolating with .format
or concatenating strings are fragile ways to do it. For instance if you do 'var foo = "' + foo + '"'
this will break as soon as your foo
variable has a double quote in it (same with 'var foo = "{0}"'.format(foo)
). Using json.dumps
is going to avoid this and will work in most cases but it does not take care of something like this:
el = driver.find_element(".something")
// Do stuff with el on the Python side.
driver.execute_script("""
var el = arguments[0];
// Do something with el on the JavaScript side.
""")
Selenium知道如何在找到JavaScript对象时将其转换为DOM对象时将其转换为Python对象. json.dumps
不会执行此操作.
Selenium knows how to convert the Python object it gives you when you find an object to a DOM object on the JavaScript side. json.dumps
does not do this.
这篇关于如何在JavaScript中使用python变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!