简体   繁体   中英

Java selenium javascript executor returning empty array

I'm trying to run a javascript function I wrote to collect all comments of an HTML site via the xpath(requirement).
The function pasted in a browser, ofc. without the 'return' statement, works perfectly fine.
But when executed via the selenium ' javascriptexecutor ' it returns an empty array.
I know that you have to put the javascript statements into a " code "+ form but for the sake of readability I formatted my code like below.
I hope someone can help me with this:)

ChromeDriver driver = new ChromeDriver();
String url = "AprivateSamplePage";
driver.get(url);
JavascriptExecutor js = (JavascriptExecutor) driver;
String text = (String)  js.executeScript("return nodes =[];
xPathResult=document.evaluate('//comment()',document,null,XPathResult.ANY_TYPE, null);
nodes =[]; 
node = xPathResult.iterateNext();
while (node) {nodes.push(node.textContent);
node =  xPathResult.iterateNext();}nodes;").toString();
System.out.print(text);

And The Output looks like this:

Only local connections are allowed.
Okt 30, 2018 8:56:07 AM org.openqa.selenium.remote.ProtocolHandshake createSession
INFORMATION: Detected dialect: OSS
[]
Process finished with exit code 0

You are executing the script js.executeScript("return nodes =[];"); only. The rest of the script is ignored after that return statement. Hence you receive an empty array.

Regarding executeScript(String) javaDoc documentation, your script code is wrapped and executed as body of an anonymous function like this:

function f() {
    return nodes = [];
    xPathResult = document.evaluate('//comment()', document, null, XPathResult.ANY_TYPE, null);
    nodes = [];
    node = xPathResult.iterateNext();
    while (node) {
        nodes.push(node.textContent);
        node = xPathResult.iterateNext();
    }
    nodes;
}();

As you know, each script statement is separated by ";". As the first statement is a return statement, the function ends there and returns the empty array as result.

In your browser console, the script works as expected because it does not stop at the return statement, but prints out the finale statements' nodes; value.

You should move the return from the first to the last statement:

xPathResult = document.evaluate('//comment()', document, null, XPathResult.ANY_TYPE, null);
nodes = [];
node = xPathResult.iterateNext();
while (node) {
    nodes.push(node.textContent);
    node = xPathResult.iterateNext();
}

return nodes;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM