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

标签 java javascript selenium selenium-webdriver

我正在使用 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 文件放在我的本地主机上,我使用 file:///调用它,并在外部服务器上试过它。没有骰子。

此外,在 Java 部分,我尝试使用该技巧附加“scr”+“ipt”,但它仍然无效。当我使用 Firefox 的检查元素检查 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);");

关于java - 如何使用 selenium 将 javascript 文件加载到 DOM 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17385779/

相关文章:

java - 每次更改src/main/resources下的属性文件时,都必须重新构建Jar

java - "Java programming language type"的定义是什么

javascript - MongoDB:SyntaxError:属性列表后缺少}

python - find_elements_by_* 函数是否总是反射(reflect) DOM 顺序?

selenium - 如何通过Selenium-webdriver和Java从剪贴板粘贴文本?

selenium - 按子文本选择节点

java - Android 中 ImageButton 上的 ClickEvent?

javascript - 出现错误 : [$injector:modulerr] when adding angularjs. min.js - Angularjs

javascript - Lodash 从对象中过滤掉非法项目

java - Webview加载url但在默认浏览器中打开内容?