如何使用selenium将javascript文件加载到DOM中?
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了如何使用selenium将javascript文件加载到DOM中?,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1925字,纯文字阅读大概需要3分钟。
内容图文
![如何使用selenium将javascript文件加载到DOM中?](/upload/InfoBanner/zyjiaocheng/712/8c404503e4074925bdd94010a098eec3.jpg)
我正在使用Selenium WebDriver尝试将外部javascript文件插入到DOM中,而不是将整个内容输入到executeScript中.
看起来它正确地将节点放入DOM中,但它只是忽略了源,即所述源js文件上的函数不运行.
这是我的代码:
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
public class Example {
public static void main(String[] args) {
WebDriver driver = new FirefoxDriver();
driver.get("http://google.com");
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("document.getElementsByTagName('head')[0].innerHTML += '<script src=\"<PATH_TO_FILE>\" type=\"text/javascript\"></script>';");
}
}
我链接的javascript文件的代码是
alert("hi Nate");
我已将js文件放在我的localhost上,我使用file:///调用它,然后在外部服务器上尝试了它.没有骰子.
此外,在Java部分,我尝试使用该技巧附加’scr”ipt’,但它仍然无效.当我使用Firefox的inspect元素检查DOM时,我可以看到它正确加载脚本节点,所以我很困惑.
我也尝试过这个解决方案,它显然是为另一个版本的Selenium(不是webdriver)制作的,因此没有起到任何作用:Load an external js file containing useful test functions in selenium
解决方法:
根据这个:http://docs.seleniumhq.org/docs/appendix_migrating_from_rc_to_webdriver.jsp
You might be using the browserbot to obtain a handle to the current
window or document of the test. Fortunately, WebDriver always
evaluates JS in the context of the current window, so you can use
“window” or “document” directly.Alternatively, you might be using the browserbot to locate elements.
In WebDriver, the idiom for doing this is to first locate the element,
and then pass that as an argument to the Javascript. Thus:
webdriver中的以下工作也是如此?
WebDriver driver = new FirefoxDriver();
((JavascriptExecutor) driver)
.executeScript("var s=window.document.createElement('script'); s.src='somescript.js'; window.document.head.appendChild(s);");
内容总结
以上是互联网集市为您收集整理的如何使用selenium将javascript文件加载到DOM中?全部内容,希望文章能够帮你解决如何使用selenium将javascript文件加载到DOM中?所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。