Selenium:是否有类似 "New element inserted in DOM"的事件

标签 selenium selenium-webdriver

我正在测试的网站有一个通知逻辑,它会在屏幕底部显示一条消息,将其保持一秒钟,然后将其发送出去。当显示通知时,它隐藏了其他元素,这使我的测试不稳定。我尽力弄清楚通知何时显示(业务逻辑何时显示)并关闭它,但我时不时地检测到新情况,我的代码不知道何时显示通知。

有没有办法(使用 Selenium)订阅像“DOM 中插入的新元素”这样的事件。关闭回调通知将一劳永逸地解决我的问题。

最佳答案

Selenium 不支持这种开箱即用的用例,但您可以在 javascript 中使用 MutationObserver 来实现。我不知道你用什么语言来编写 selenium 测试,但在 C# 中你可以创建如下扩展方法

public static void StartWatchingForContentChange(this RemoteWebDriver driver, string containerId, int  timeout = SearchElementDefaultTimeout)
{
    driver.ExecuteScript(@"var $$expectedId = arguments[0];
__selenium_observers__ =  window.__selenium_observers__ || {};
(function(){        
var target = document.getElementById($$expectedId);
__selenium_observers__[$$expectedId] = {
        observer: new MutationObserver(function(mutations) {
            __selenium_observers__[$$expectedId].occured = true;
            __selenium_observers__[$$expectedId].observer.disconnect();
        }),
        occured:false
};
var config = { attributes: true, childList: true, characterData: true, subtree: true };
__selenium_observers__[$$expectedId].observer.observe(target, config);
})();", containerId);       
}

public static bool WasContentChanged(this RemoteWebDriver driver, string containerId)
{
    return (bool) driver.ExecuteScript( "return window.__selenium_observers__ && window.__selenium_observers__[arguments[0]].occured;", containerId)
}

您可以使用某种计时器异步调用 WasContentChanged 方法并对内容更改使用react。请阅读 MutationObserver 文档以获取更多详细信息 https://developer.mozilla.org/pl/docs/Web/API/MutationObserver

关于Selenium:是否有类似 "New element inserted in DOM"的事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41192258/

相关文章:

python - ElementNotInteractableException : Message: element not interactable error sending text in search field using Selenium Python

c# - 网页测试自动化框架中的问题

java - 迭代 LinkedHashMap 并在新行上返回每个 ‘String’ 元素

java - Selenium 在页面部分中搜索文本并单击其中的按钮

python - 尝试替代 xpath,否则继续

python - 使用 Python Selenium 获取跨度文本

java - 定位元件故障

java - WebDriverWait 在 Selenium 4 中已弃用

java - 将方法添加到数组列表并动态调用方法

java - Selenium 单击“添加文件”按钮打开新窗口