gpt4 book ai didi

java - 使用WebDriver JS Executor执行.js文件 --> 空指针异常

转载 作者:行者123 更新时间:2023-12-01 14:22:24 34 4
gpt4 key购买 nike

我正在尝试实现一个我在网上找到的脚本,该脚本可以自动将 jQuery 加载到当前没有它们的网站中。我正在使用 Selenium Webdriver 的 JS Executor 功能;但是,它不断返回空指针异常。我试图到处寻找答案,但似乎无法理解发生了什么。给出了什么?

/** Browser automation driver for this test instance. */
private WebDriver driver;

/** JavaScript Executor for this test instance. */
private JavascriptExecutor js = (JavascriptExecutor) driver;

//...Firefox browser initialized here

public void JQuerify(final String Url){
ReporterNG.log("Opening a webpage at: " + Url);
driver.get(Url);

ReporterNG.log("Converting JS file to a String");

String jQueryLoader = getLoadJQuery();

// give jQuery time to load asynchronously
driver.manage().timeouts().setScriptTimeout(10, TimeUnit.SECONDS);

js.executeAsyncScript(jQueryLoader);
//THE PROBLEM ALWAYS OCCURS WITH THIS ^^^^^

ReporterNG.log("jQuery loaded!");
//THIS NEVER PRINTS OUT DUE TO THE ERROR ^^^^
}

/** dynamically load jQuery */
public static String getLoadJQuery(){
String LoadJQuery = "(function(jqueryUrl, callback) {\n" +
"if (typeof jqueryUrl != 'string') {" +
"jqueryUrl = 'https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js';\n" +
"}\n" +
"if (typeof jQuery == 'undefined') {\n" +
"var script = document.createElement('script');\n" +
"var head = document.getElementsByTagName('head')[0];\n" +
"var done = false;\n" +
"script.onload = script.onreadystatechange = (function() {\n" +
"if (!done && (!this.readyState || this.readyState == 'loaded'\n" +
"|| this.readyState == 'complete')) {\n" +
"done = true;\n" +
"script.onload = script.onreadystatechange = null;\n" +
"head.removeChild(script);\n" +
"callback();\n" +
"}\n" +
"});\n" +
"script.src = jqueryUrl;\n" +
"head.appendChild(script);\n" +
"}\n" +
"else {\n" +
"callback();\n" +
"}\n" +
"})(arguments[0], arguments[arguments.length - 1]);\n";
return LoadJQuery;
}

任何帮助将不胜感激,因为我在 JS Executor 的其他类似应用程序中遇到了同样的问题。谢谢!

最佳答案

使 JavascriptExecutor 实例成为该方​​法的本地实例。

JavascriptExecutor js = (JavascriptExecutor) driver;
// give jQuery time to load asynchronously
driver.manage().timeouts().setScriptTimeout(10, TimeUnit.SECONDS);
js.executeAsyncScript(jQueryLoader);

关于java - 使用WebDriver JS Executor执行.js文件 --> 空指针异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17431251/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com