Selenium:如何在加载/执行页面的任何其他脚本之前将Javascript插入/执行到页面中? [英] Selenium: How to Inject/execute a Javascript in to a Page before loading/executing any other scripts of the page?

查看:691
本文介绍了Selenium:如何在加载/执行页面的任何其他脚本之前将Javascript插入/执行到页面中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Selenium python Webdriver来浏览某些页面.我想在加载和执行任何其他Javascript代码之前将javascript代码注入页面.另一方面,我需要将我的JS代码作为该页面的第一个JS代码执行.硒有办法做到这一点吗?

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!

推荐答案

如果无法修改页面内容,则可以使用代理或在浏览器中安装的扩展程序中使用内容脚本.在selenium中执行此操作,您将编写一些代码,将脚本作为现有元素的子元素之一注入,但是在页面加载之前(当驱动程序的get()调用返回时)您将无法运行脚本.

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 () { ... })();" ...

文档未指定代码开始执行的时间.您可能希望它在DOM开始加载之前就出现,以便只能通过代理或扩展内容脚本路由来满足保证.

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.

如果可以使用最少的工具检测页面,则可以检测到特殊的url查询参数并加载其他内容,但是您需要使用内联脚本来实现.伪代码:

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:

 <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>
    ...

这篇关于Selenium:如何在加载/执行页面的任何其他脚本之前将Javascript插入/执行到页面中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆