【问题标题】:How do i execute JavaScript code in Python Selenium and then call it back in my Python code?如何在 Python Selenium 中执行 JavaScript 代码,然后在我的 Python 代码中调用它?
【发布时间】:2018-11-17 21:23:35
【问题描述】:

这里我有一些 Python 代码可以打开我的 JavaScript 文件并将其执行到网页中。我看到帖子说execute_async_script() 允许在 JavaScript 中处理回调,但我不太明白。

with open("script.js") as f:
    script_source = f.read()

wait.until(EC.element_to_be_clickable((By.CLASS_NAME, "textArea-2Spzkt")))

script_exc = driver.execute_async_script(script_source)
print("test", script_exc)

这是 Selenium 注入的 JavaScript。它侦听特定类中的更改,并在检测到更改时将字符串输出到控制台。

// Select the node that will be observed for mutations
var targetNode = document.getElementsByClassName('messagesWrapper-3lZDfY')[0];

// Options for the observer (which mutations to observe)
var config = { attributes: false, childList: true, subtree: true };

// Callback function to execute when mutations are observed
var callback = function(mutationsList, observer) {
    for(var mutation of mutationsList) {
        if (mutation.type == 'childList') {
            console.log('A child node has been added or removed.');
        }
        else if (mutation.type == 'attributes') {
            console.log('The ' + mutation.attributeName + ' attribute was modified.');
        }
    }
};

// Create an observer instance linked to the callback function
var observer = new MutationObserver(callback);

// Start observing the target node for configured mutations
observer.observe(targetNode, config);

当检测到节点更改时,我希望能够让 JavaScript 在 Python 控制台中返回一个字符串 "node change detected"。所以在我的 Python 代码中写着print("test", script_exc),我希望它打印testnode change detected。作为一个整体,我对 JavaScript 还是很陌生,对 Python 也很陌生。我看到有人说要在 JavaScript 中使用arguments[0],但我不知道这与我的 Python 代码有何关联。

【问题讨论】:

    标签: javascript python-3.x selenium-webdriver


    【解决方案1】:

    在 JavaScript 中使用 arguments[0] 表示回调已完成。

    script="var a = 1;"
    // if return a, use execute_script()
    a = driver.execute_script("return a;")
    // or use execute_async_script()
    async_script="return arguments[0](a)"
    a = driver.execute_async_script(async_script)
    

    【讨论】:

      猜你喜欢
      • 2021-01-27
      • 2014-02-17
      • 1970-01-01
      • 2021-02-14
      • 1970-01-01
      • 2016-12-02
      • 2012-04-05
      • 1970-01-01
      • 2020-11-06
      相关资源
      最近更新 更多