Home > Mobile >  Can Selenium web driver track web page changes?
Can Selenium web driver track web page changes?

Time:12-19

Each time the web page has changes I want to get the text elements of web page. So for having the text elements, here is my method:

public void getContentPage(WebDriver driver) {
    WebDriverWait wait = new WebDriverWait(driver, 15);
    WebElement element = wait.until(ExpectedConditions.visibilityOfElementLocated(By.tagName("body")));
    System.out.println(element.getText());

}

What I need is a kind of listener using Selenium to call the above method each time there are changes in HTML body content:

public void listen (WebDriver driver) {
    // some kind of listner that waits for any changes to happen in HTML
    if (changed) getContentPage(driver);
    else keeplistning()

}

CodePudding user response:

I'm not sure there is a way to track all and every change on the page and I'm not sure you want this since this will trigger you on many irrelevant changes.
What can be useful here is to track changes on some specific relevant element(s).
So, to wait until some specific element is changed you can use refreshed ExpectedCondition like the following:

WebElement button = driver.findElement(By.id("myBtn"));
wait.until(ExpectedConditions.refreshed(button));

In case you wish to monitor several elements it will be something like this:

wait.until(ExpectedConditions.or(
                    ExpectedConditions.refreshed(element1),
                    ExpectedConditions.refreshed(element2),
                    ExpectedConditions.refreshed(element3)));

You should, of cause, wrap this in some method according to your specific code use. I wrote here the basic idea only.
UPD
To track the entire page you can use driver.getPageSource(); method. Polling the page state with some time interval and comparing the value of previous result of this method with the new result will give you indication of any page content change.

  • Related