我正在尝试运行编写的 javascript 函数,以通过xpath(要求)收集HTML站点的所有注释。
粘贴在浏览器中的功能,ofc。没有'return'语句,效果很好。
但是当通过硒' javascriptexecutor '执行时,它将返回一个空数组。
我知道您必须将javascript语句放入“ code ” +格式中,但是为了便于阅读,我将代码格式化如下。
我希望有人可以帮助我:)
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);
输出看起来像这样:
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
答案 0 :(得分:1)
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;