微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何使用selenium将javascript文件加载到DOM中?

我正在使用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);");

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐