如果无法修改页面内容,则可以使用代理服务器,或在浏览器中安装的扩展程序中使用内容脚本.在硒内容中,您将编写一些将脚本作为现有元素的子项之一注入的代码,但是在加载页面之前(当您的驱动程序的get()调用返回时),您将无法运行该脚本.
String name = (String) ((JavascriptExecutor) driver).executeScript(
"(function () { ... })();" ...
文档在代码开始执行的时刻未指定.您需要在DOM开始加载之前,以便保证可能只能使用代理或扩展内容脚本路由才能满足.
如果您可以使用最小的线束来调整页面,则可能会检测到特殊的url查询参数的存在并加载其他内容,但是您需要使用内联脚本.伪代码:
(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);
}
})();
...