【问题标题】:Python, With Selenium how to add a JS function to the page? [duplicate]Python,使用 Selenium 如何在页面中添加 JS 函数? [复制]
【发布时间】:2018-12-06 09:49:39
【问题描述】:

我正在尝试向页面添加一些 JS 函数,但不知道如何在不将函数分配给窗口对象的情况下做到这一点。

以下将起作用:

driver.execute_script("console.log('lalala');")
driver.execute_script("function momo(){console.log('lalala')};momo();")

但是尝试做:

driver.execute_script("function momo(){console.log('lalala')};")
driver.execute_script("momo();")

会失败:

WebDriverException: Message: unknown error: momo is not defined

我知道将函数分配给窗口:

driver.execute_script("window.momo = function(){console.log('lalala')};")

会解决问题,但也许还有其他方法可以解决?

谢谢。

【问题讨论】:

  • 将函数添加到窗口是一个优雅的解决方案。您是否遇到了具体问题?

标签: python selenium


【解决方案1】:

也许这回答了这个问题:

driver.execute_script("window.momo = () => console.log('lalala');")

我只是用更现代的语法重写它。

【讨论】:

  • 这与问题中的功能相同。但更优雅......我仍然认为没有办法避免在脚本中使用window
【解决方案2】:

也许你可以创建script 元素

driver.execute_script("""
(function(){
    s = document.createElement('script');
    s.textContent = 'function momo(){console.log("lalala")};';
    document.body.appendChild(s);
})();
""")
driver.execute_script("momo();")

【讨论】:

    【解决方案3】:

    您正在尝试向窗口 dom 引入一个新元素,因此出现错误:

    WebDriverException:消息:未知错误:未定义 momo

    除非您尝试操纵现有元素,否则您的解决方案可能是唯一的解决方案!

    换句话说,您可以将 JS 函数添加到页面上已经存在的任何元素。

    这就是window dom的作用域的思路。

    阅读此answer here,您可以了解更多。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-09-22
      • 2015-11-12
      • 1970-01-01
      • 1970-01-01
      • 2015-06-03
      • 2021-08-18
      • 1970-01-01
      相关资源
      最近更新 更多