我使用selenium python webdriver来浏览一些页面。我想在加载和执行任何其他javascript代码之前将一个Javascript代码注入到页面中。另一方面,我需要我的JS代码作为该页面的第一个JS代码执行。有没有办法通过硒做到这一点?
我用谷歌搜索了几个小时,但我找不到任何合适的答案!
发布于 2015-11-23 08:15:14
如果您不能修改页面内容,您可以使用代理,或使用浏览器中安装的扩展中的内容脚本。在selenium中执行此操作时,您需要编写一些代码,将脚本作为现有元素的子元素之一进行注入,但是在加载页面之前(当驱动程序的get()
调用返回时),无法运行该脚本。
String name = (String) ((JavascriptExecutor) driver).executeScript(
"(function () { ... })();" ...
文档没有指定代码开始执行的时间。您可能希望它在DOM开始加载之前完成,这样保证可能只通过代理或扩展内容脚本路由才能满足。
如果您可以使用最小的线束来检测您的页面,您可能会检测到存在特殊的url查询参数并加载额外的内容,但您需要使用内联脚本来执行此操作。伪码:
<html>
<head>
<script type="text/javascript">
(function () {
if (location && location.href && location.href.indexOf("SELENIUM_TEST") >= 0) {
var injectScript = document.createElement("script");
injectScript.setAttribute("type", "text/javascript");
//another option is to perform a synchronous XHR and inject via innerText.
injectScript.setAttribute("src", URL_OF_EXTRA_SCRIPT);
document.documentElement.appendChild(injectScript);
//optional. cleaner to remove. it has already been loaded at this point.
document.documentElement.removeChild(injectScript);
}
})();
</script>
...
发布于 2015-11-22 19:36:02
如果您想在浏览器解析和执行页面之前将某些内容注入到页面的html中,我建议您使用诸如Mitmproxy之类的代理。
发布于 2019-06-27 19:20:44
所以我知道已经有几年了,但我已经找到了一种方法,可以在不修改网页内容和使用代理的情况下做到这一点!我使用的是nodejs版本,但该API可能也适用于其他语言。您想要做的事情如下
const {Builder, By, Key, until, Capabilities} = require('selenium-webdriver');
const capabilities = new Capabilities();
capabilities.setPageLoadStrategy('eager'); // Options are 'eager', 'none', 'normal'
let driver = await new Builder().forBrowser('firefox').setFirefoxOptions(capabilities).build();
await driver.get('http://example.com');
driver.executeScript(\`
console.log('hello'
\`)
“渴望”这个选项对我来说很有效。您可能需要使用“无”选项。文档:https://seleniumhq.github.io/selenium/docs/api/javascript/module/selenium-webdriver/lib/capabilities_exports_PageLoadStrategy.html
编辑:请注意,Chrome中还没有实现'eager‘选项...
https://stackoverflow.com/questions/31354352
复制相似问题