我想在selenium上使用MutationObserver来观察元素的变化。
但是observe()
中出现了以下错误:
Uncaught TypeError: Failed to execute 'observe' on 'MutationObserver': parameter 1 is not of type 'Node'.
我找到了有关错误的信息。 'observe' on 'MutationObserver': parameter 1 is not of type 'Node'
根据上面的stackoverflow页面,在加载dom之前调用getElement ...函数时会发生错误。
所以我尝试了等到可见的dom可见的方式, 但是错误发生了。
我正在使用
代码:
main.py:
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
options = Options()
options.binary_location = '/Applications/Google Chrome Canary.app/Contents/MacOS/Google Chrome Canary'
options.add_experimental_option("detach", True)
#options.add_argument('--headless')
with open("execute_script.js") as f:
script_source = f.read()
driver = webdriver.Chrome("./chromedriver", chrome_options=options)
driver.get("example.com/index.html")
close_icons = driver.find_elements_by_css_selector("i.CloseIcon")
if len(close_icons) >= 1:
for v in close_icons:
if v.is_displayed():
v.click()
driver.execute_script(script_source)
execute_script.js:此脚本作为main.py中的执行脚本加载。
let body = document.getElementsByTagName("body")[0];
let script = document.createElement("script");
script.type = "application/javascript";
let str = `
let dom = document.getElementById('last-last');
function getDesiredDom() {
dom = document.getElementById("last-last");
if (!dom) {
console.log("Desired dom does not exist yet")
setTimeout(getDesiredDom, 500);
}
}
getDesiredDom();
let ws = new WebSocket("ws://localhost:6788/");
ws.addEventListener("message", (message) => {
console.log(message.data);
});
ws.onerror = (error) => console.log(error);
let observer_config = {childList: true, attributes: true, characterData: true};
let observer = new MutationObserver((mutation) => {
for (v of mutation) {
if (v.type === "childList") {
for (x of v.addedNodes) {
if (x.nodeName === '#text') {
console.log(x.nodeValue);
ws.send(x.nodeValue);
}
}
}
}
});
observer.observe(dom, observer_config);
`
script.innerHTML = str;
body.appendChild(script)