首页 > 解决方案 > Selenium:等到属性值改变

问题描述

我在网页中有图像,其 src 在一段时间后更改,在 src 更改后可能有两个可能的值(时间可能会有所不同)img_src_success 或 img_src_failed

我在下面添加了代码以等待 src 更改但它不起作用并给出错误。

 WebDriverWait wait = new WebDriverWait(driver, 120);
 wait.until(ExpectedConditions.attributeToBe(image_src, "src",img_src_success );  

其中 image_src = WebElement
src = 属性
img_src_success = 字符串值“/src/image/success.png” img_src_running= “/src/image/failed.png”的字符串值”

上面的代码给出错误

org.openqa.selenium.StaleElementReferenceException:过时的元素引用:元素未附加到页面文档。

请建议我做错了什么或任何其他方式来做到这一点。

标签: seleniumtestingautomation

解决方案


StaleElementException当元素被删除或从 DOM 分离时抛出。再做findElement一次可能会解决问题。有一个ExpectedConditions.attributeToBe接受By定位器的变体。使用它可确保每次在进行检查之前检索元素并可能解决问题。

您可以使用wait.until自己的ExpectedCondition,每次都可以获取元素并检查StaleElementReferenceException. 如下所示:

    wait.until(new ExpectedCondition<Boolean>() {
        @Override
        public Boolean apply(WebDriver input) {
            try {
                WebElement deployed_row = Report_id
                        .findElement(By.xpath("//div[(@class = 'gridxRow') and (@rowindex = '0')]"));
                WebElement table = deployed_row.findElement(By.className("gridxRowTable"));
                WebElement image_src = table.findElement(By.xpath("//tbody/tr/td[2]/div/div/span/img"));
                return image_src.getAttribute("src").equals(img_src_success);
            } catch (StaleElementReferenceException e) {
                return false;
            }
        }
    });

推荐阅读