简体   繁体   English

Selenium:如何跟踪DOM操作以查找元素的可见性?

[英]Selenium: How to track DOM manipulation to find visibility of an element?

Is there a possibility of watching a webpage for events like: an element has been made visible? 是否有可能观看网页上的事件,例如:某个元素已可见?

And is this possible using selenium? 使用硒有可能吗?

For example, If I define a timeline for watching a webpage from startTime to endTime. 例如,如果我定义了一个时间表,以观看从startTime到endTime的网页。 From startTime to endTime, different webpage events could be captured, which includes dom manipulations ( for example: html element has got added and been made visible ). 从startTime到endTime,可以捕获不同的网页事件,其中包括dom操作(例如:html元素已添加并变得可见)。 Once endTime is reached, I would iterate over the list of events and I could validate a particular event has occurred or not. 到达endTime后,我将遍历事件列表,并可以验证是否发生了特定事件。

In my case, I would like to find out if an html element has been made visible or not. 就我而言,我想了解一个html元素是否可见。

The usual way to find out is to use webdriver's API to check visibility of an element, with some timeout. 找出问题的常用方法是使用webdriver的API来检查元素的可见性,但会超时。

But, I would like to capture different events and have some callbacks, thereby validating that some expected event has occurred. 但是,我想捕获不同的事件并进行一些回调,从而验证是否发生了某些预期事件。

[UPDATE]: Do we have a support for MutationObserver in Selenium? [更新]:Selenium中是否支持MutationObserver

Yes, you use explicit wait as shown in the WebDriver Documentation . 是的,您可以使用WebDriver文档中所示的显式等待。

The ExpectedConditions class provides many useful element states such as ElementToBeVisible , ElementToBeClickable , etc. ExpectedConditions类提供了许多有用的元素状态,例如ElementToBeVisibleElementToBeClickable等。

That should do the trick. 这应该够了吧。

Here's a sample of what you can do: 以下是您可以做什么的示例:

WebDriverWait wait = new WebDriverWait(driver, 10); // how many seconds
wait.until(ExpectedConditions.elementToBeClickable(myPage.getButton()));

For more sophisticated things you can provide your own Function for WebDriverWait , ie: 对于更复杂的事情,您可以为WebDriverWait提供自己的Function ,即:

wait.until(o -> {
    return driver.getWindowHandles().stream().collect(Collectors.toList()).get(tabNo);
});

Selenium doesn't support events, so you probably should move to another tool like puppetter which seems to support events. Selenium不支持事件,因此您可能应该转到另一个似乎支持事件的工具puppetter That said, it's still possible to record events with a script injection by storing all the events in a variable in the page: 也就是说,通过将所有事件存储在页面的变量中,仍然可以通过脚本注入来记录事件:

jse.executeScript(
  "var window.__events = [];" +
  "new MutationObserver(function(mutations) {" +
  "    mutations.forEach(function(mutation) {" +
  "        window.__events.push(mutation);" +
  "    });" +
  "})).takeRecords();");

Then simply return the list: 然后只需返回列表:

Object events = jse.executeScript("return window.__events;");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM