【问题标题】:Selenium : wait until attribute value changedSelenium:等到属性值改变
【发布时间】:2018-08-29 04:49:55
【问题描述】:

我在网页中有图片,其 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:过时的元素 参考:元素未附加到页面文档。

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

【问题讨论】:

  • 每当人们遇到陈旧元素问题时,我强烈建议他们使用 WATIR,WATIR 处理陈旧元素问题非常好,WATIR 是位于 Ruby Selenium Binding 上的包装器。如果您的项目还没有走得太远,请考虑使用 WATIR。
  • 你试过 xpath - contains(),starts-with(),ends-with() 方法吗???你能显示一次img标签的html吗??
  • @shruti 它是循环内的句柄?如果是这样,您需要与相关的 HTML 共享循环代码。
  • @amit ,我尝试添加 html 图像标签,但它给出了我无法发布的错误。如何在 wait.until(ExpectedConditions.attributeToB 中添加包含、以 etc 开头。你能解释一下吗?
  • @Amit 如何使用这些 xpath 来解决问题?陈旧元素意味着对元素的引用由于页面刷新或页面导航而丢失

标签: selenium testing automation


【解决方案1】:

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

【讨论】:

  • 要查找我正在使用父 WebElement 的图像元素,我没有唯一的 By 定位器。我的代码是: WebElement deploy_row=Report_id.findElement(By.xpath("//div[(@class= 'gridxRow') and (@rowindex = '0')]")); WebElement table = deploy_row.findElement(By.className("gridxRowTable")); WebElement image_src=table.findElement(By.xpath("//tbody/tr/td[2]/div/div/span/img"));
  • 您可以实现自己的 ExpectedCondition,它可以执行所有 findElement 调用,然后检查属性。
  • 是的。根据条件初始化您的变量。
  • 如何使用同一段代码,其中图像 src 可以基于特定条件 "img_src_success" 或 "img_src_failed" 有两个值?但是当我等待元素时在运行时决定..我尝试添加 if else 代替 try 块中的 return 但它不起作用:(
猜你喜欢
  • 1970-01-01
  • 2017-10-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-01
  • 2021-12-20
相关资源
最近更新 更多