Selenium Javascript 执行程序返回 null
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17910632/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Selenium Javascript executor returns null
提问by theJ
I have the following JavaScript code returning null
when ran through Selenium JavascriptExecutor
. However, the same code when ran in Firefox developer console returned a value.
我null
在运行 Selenium 时返回以下 JavaScript 代码JavascriptExecutor
。但是,在 Firefox 开发者控制台中运行的相同代码返回了一个值。
function tmp(){
var attrb = jQuery(jQuery("[name='q']")[0]).attr('type');
if(typeof attrb !== 'undefined' && attrb !== false){
return attrb;
} else {
return '';
}
}
tmp();
The below is my WebDriver code with the JS the same as above:
下面是我的 WebDriver 代码,JS 与上面相同:
JavascriptExecutor jsExec = (JavascriptExecutor)driver;
Object inpType =
jsExec.executeScript("function tmp(){...}tmp();");
System.out.println("Type: " + inpType);
Above outputs null
instead of "text" string. Any ideas?
以上输出null
而不是“文本”字符串。有任何想法吗?
回答by Gangadhar
you need to use return tmp()instead of tmp()in executeScript() method. Find the related reference driver.executeScript() returns NullPointerException for simple javascript
您需要在 executeScript() 方法中使用return tmp()而不是tmp()。查找相关参考 driver.executeScript() 返回 NullPointerException for simple javascript
回答by Timo Türschmann
The problem is that you execute two statements in executeScript()
. The function definition of tmp() and the function call of tmp().
问题是你在executeScript()
. tmp()的函数定义和tmp()的函数调用。
I don't know the details, but the function definition seems to return null.
我不知道细节,但函数定义似乎返回空值。
Since executeScript returns the first value that can be returned, it returns null. If you don't define the function and write the code inline, it will work.
由于 executeScript 返回第一个可以返回的值,因此它返回 null。如果您不定义函数并内联编写代码,它将起作用。
JavascriptExecutor jsExec = (JavascriptExecutor) driver;
Object inpType = jsExec
.executeScript("var attrb = jQuery(jQuery(\"[name='q']\")[0]).attr('type');"+
"if(typeof attrb !== 'undefined' && attrb !== false)" +
"{return attrb;}" +
"else{return '';}");
System.out.println("-------------- Type: " + inpType);
This should print your expected value.
这应该打印您的预期值。
Edit: Also, your posted code doesn't escape the ""
around [name='q']
. This ends the string and causes syntax errors.
编辑:此外,您发布的代码不会逃避""
周围的[name='q']
. 这会结束字符串并导致语法错误。
回答by Mohammad Noor
You should add a return
statement to the result you want to return from inside the jsExec.executeScript(...)
您应该在return
要从内部返回的结果中添加一条语句jsExec.executeScript(...)