【发布时间】: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),我希望它打印test 和node change detected。作为一个整体,我对 JavaScript 还是很陌生,对 Python 也很陌生。我看到有人说要在 JavaScript 中使用arguments[0],但我不知道这与我的 Python 代码有何关联。
【问题讨论】:
标签: javascript python-3.x selenium-webdriver