[Python] Is there a way to use MutationObserver JavaScript API in selenium

Discussão em 'Python' iniciado por Stack, Abril 26, 2025.

  1. Stack

    Stack Membro Participativo

    I want to use MutationObserver on selenium to observe change of the element.

    But following error have occurred in observe():

    Uncaught TypeError: Failed to execute 'observe' on 'MutationObserver': parameter 1 is not of type 'Node'.


    I found information about the error. 'observe' on 'MutationObserver': parameter 1 is not of type 'Node'

    According to above stackoverflow page, the error occure when invoke getElement... function before loading dom.

    So I tried the way that wait until desired dom be visible, But the error occur.

    I am using

    • Python3.6.3
    • selenium3.6
    • Chrome 64.0.3248.0 (Official Build) canary.

    Codes:

    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: this script is loading as a execute script in 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)

    Continue reading...

Compartilhe esta Página