13

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();

以下是我的 WebDriver 代码,其 JS 与上面相同:

JavascriptExecutor jsExec = (JavascriptExecutor)driver;
Object inpType = 
       jsExec.executeScript("function tmp(){...}tmp();");
System.out.println("Type: " + inpType);

以上输出null而不是“文本”字符串。有任何想法吗?

4

3 回答 3

20

您需要在 executeScript() 方法中使用return tmp()而不是tmp() 。查找相关参考 driver.executeScript() 返回 NullPointerException for simple javascript

于 2014-02-18T07:32:11.957 回答
2

return您应该在要从内部返回的结果中添加一条语句jsExec.executeScript(...)

于 2019-03-11T11:48:00.860 回答
1

The problem is that you execute two statements in executeScript(). The function definition of tmp() and the function call of 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.

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.

于 2013-07-29T09:06:25.690 回答