[英]Track changes within DOM element with MutationObserver Python
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).我想检索比赛开始前的秒数(没有现场比赛 atm,但想法是一样的)。 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.现在我想使用MutationObserver
来跟踪这个元素的变化。 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?它应该在控制台中连续打印“时间在滴答作响” ,对吗?
What am I doing wrong?我究竟做错了什么? And is there also a possibility that the output is printed in my python-script?是否还有可能在我的 python 脚本中打印输出?
querySelectorAll is not live. querySelectorAll 未上线。 It's returns representations of what the dom was and you're monitoring that snapshot.它返回 dom 是什么的表示,并且您正在监视该快照。 You need to use getElementsByClassName to hook onto a live element.您需要使用 getElementsByClassName 来挂钩活动元素。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.