【发布时间】:2019-08-03 02:29:48
【问题描述】:
总结
我想找到一种方法,使用Selenium 的JavascriptExecutor 将<script> 标签添加到DOM 的头部,或者任何其他方式都可以。
我尝试了很多方法,也发现了一些类似的主题,但没有一个能解决我的问题,这就是为什么我觉得有必要在这里提问。
例如:
Suggested solutions in this question 没有解决我的问题。有人说它对他们有用,但不,它不适合我。
我一直在尝试执行什么?
这是我要执行的代码的小sn-p:
WebDriver driver = new FirefoxDriver();
JavascriptExecutor jse = (JavascriptExecutor) driver;
jse.executeScript("var s = document.createElement('script');");
jse.executeScript("s.type = 'text/javascript';");
jse.executeScript("s.text = 'function foo() {console.log('foo')}';");
jse.executeScript("window.document.head.appendChild(s);");
我只是跳过了上面的代码,您使用driver.get() 等导航到网页,然后尝试执行脚本。
另外,s.text 将包含我想要使用的实际脚本,所以我只是放了一个 foo() 函数来给出想法。
上面的代码在运行时会抛出这个错误:
Exception in thread "main" org.openqa.selenium.JavascriptException: ReferenceError: s is not defined
到目前为止,我已经尝试了所有可以在 Internet 上找到的解决方案,但似乎都没有。
【问题讨论】:
-
在 JavaScriptExecutor 中声明的变量在其脚本完成后是否仍然存在?可能是错的,但我不这么认为。
-
不,它没有。那就是问题所在。你可以阅读我上面得到的错误。它说变量未定义。除此之外,我还尝试注入整个 JavaScript 文件,但这也不起作用。
标签: java selenium selenium-webdriver