[Python] Track changes within DOM element with MutationObserver Python

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

  1. Stack

    Stack Membro Participativo

    I found a website that pushes darts scores. Each time a new score is published, I would like to be notified.

    import time
    import selenium
    from selenium import webdriver
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support.ui import WebDriverWait

    URL = 'https://live.dartsdata.com/'
    driver = webdriver.Chrome('/Users/hjam/downloads/chromedriver')
    driver.get(URL)

    time.sleep(1)
    matches = driver.find_elements(By.XPATH, ".//*[@class='sr-match__wrapper srt-base-1 sr-ml-list__match']")
    matches[0].click()


    I want to retrieve the seconds until the match starts (there are no live matches atm, but idea is the same). I see that this data point is located in

    seconds = driver.find_elements(By.XPATH, ".//*[@class='sr-lmt-0-ms-countdown__time srt-primary-7 srm-large']")[-1]


    Now I want to use a MutationObserver to track the changes of this element. Each time the element changes, I want it to be printed. Using the example of docs I write the following

    driver.execute_script("""
    const targetNode = document.querySelector('#content1 > div.sr-lmt-plus__comp.srm-double.srm-isLmt > div > div > div > div > div > div > div.sr-lmt-wrap > div > div.sr-lmt-22-state > div.sr-bb.sr-lmt-matchstatus.sr-ltr.sr-lmt-matchstatus--small > div > div > div.sr-lmt-matchstatus__slider.sr-slider-flex__slider > div > div > div.sr-lmt-setsports-ms-matchstatus__row.sr-lmt-setsports-ms-matchstatus__countdown-wrapper > div > div.sr-lmt-0-ms-countdown__row > div:nth-child(4)');
    const config = { attributes: true, childList: true, subtree: true };

    const callback = function(mutationsList, observer) {
    for(const mutation of mutationsList) {
    console.log('Time is ticking');
    }
    };
    const observer = new MutationObserver(callback);
    observer.observe(targetNode, config);
    """)


    This yields no error, but nothing happens. It should print continuously 'time is ticking' in the Console right?

    [​IMG]

    What am I doing wrong? And is there also a possibility that the output is printed in my python-script?

    Continue reading...

Compartilhe esta Página