【问题标题】:Can Selenium web driver track web page changes?Selenium 网络驱动程序可以跟踪网页更改吗?
【发布时间】:2022-01-21 03:24:42
【问题描述】:

每次网页发生变化时,我都想获取网页的文本元素。因此,对于拥有文本元素,这是我的方法:

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());

}

我需要的是一种使用Selenium的监听器,每次HTML正文内容发生变化时调用上述方法:

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

}

【问题讨论】:

  • 这是个好问题。

标签: java html selenium selenium-webdriver selenium-chromedriver


【解决方案1】:

我不确定是否有方法可以跟踪页面上的所有更改,我不确定您是否需要这样做,因为这会触发您进行许多不相关的更改。
这里有用的是跟踪某些特定相关元素的变化。
因此,要等到某些特定元素发生更改,您可以使用 refreshed ExpectedCondition,如下所示:

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

如果您希望监控多个元素,它将是这样的:

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

当然,您应该根据您的特定代码使用情况将其包装在某种方法中。我在这里只写了基本的想法。
UPD
要跟踪整个页面,您可以使用driver.getPageSource(); 方法。以某个时间间隔轮询页面状态并将此方法的先前结果的值与新结果的值进行比较,将为您提供任何页面内容更改的指示。

【讨论】:

  • 太棒了,感谢您提供的信息,但我想要的是我不在乎哪个元素已更改,换句话说 => 如果 html 中有任何更改,请调用从 body 返回新文本的函数。
  • 好的,我明白了。正如我在更新的答案中提到的,您可以为此使用 driver.getPageSource(); 方法。我希望现在它会给你你正在寻找的东西
猜你喜欢
  • 1970-01-01
  • 2018-10-20
  • 2011-07-11
  • 1970-01-01
  • 1970-01-01
  • 2015-07-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多