selenium调用js文件_Selenium:如何在加载/执行页面的任何其他脚本之前将Javascript插入/执行到页面中?...

I'm using selenium python webdriver in order to browse some pages. I want to inject a javascript code in to a pages before any other Javascript codes get loaded and executed. On the other hand, I need my JS code to be executed as the first JS code of that page. Is there a way to do that by Selenium?

I googled it for a couple of hours, but I couldn't find any proper answer!

解决方案

If you cannot modify the page content, you may use a proxy, or use a content script in an extension installed in your browser. Doing it within selenium you would write some code that injects the script as one of the children of an existing element, but you won't be able to have it run before the page is loaded (when your driver's get() call returns.)

String name = (String) ((JavascriptExecutor) driver).executeScript(

"(function () { ... })();" ...

The documentation leaves unspecified the moment at which the code would start executing. You would want it to before the DOM starts loading so that guarantee might only be satisfiable with the proxy or extension content script route.

If you can instrument your page with a minimal harness, you may detect the presence of a special url query parameter and load additional content, but you need to do so using an inline script. Pseudocode:

(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);

}

})();

...

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值