【问题标题】:Selenium: How to get the changing value of a webelement in a for loopSelenium:如何在 for 循环中获取 web 元素的变化值
【发布时间】:2017-10-29 17:39:52
【问题描述】:

我正在尝试获取随时间变化的 weblement 的价值。值为 -Pending, Approved, Received

当值更改为Received 时,我必须停止循环。我尝试了下面的代码,但它在一个循环中成功运行,然后在第二个循环中停止,错误为webelement not found with the given xpath

for(int i=0;i<=50;i++)
{
    String exactvalue=driver.findElement(By.xpath("//tr[2]/td")).getText();
        if (exactvalue.equals("Received"))
        {
            break;
        }
        else 
        {
        driver.navigate().refresh();
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            throw new RuntimeException("executing sleep interrupted");
        }

        }
    }

【问题讨论】:

    标签: java selenium xpath


    【解决方案1】:

    从您的代码中替换下一行。

    你的代码:

    String exactvalue=driver.findElement(By.xpath("//tr[2]/td")).getText();
    

    替换为:

    String exactvalue=driver.findElement(By.xpath("//tr["+i+"]/td")).getText();
    

    【讨论】:

    • webelement 值存在于 xpath=//tr[2]/td 中,每当 webelement 的值更改为“已接收”时,我都会尝试刷新页面 50 次并中断循环。它第一次运行良好,但第二次出现错误,提示 webelement xpath 不正确。我认为刷新页面会导致硒失去焦点。如果我尝试您的代码,它将继续在 xpath=//tr[0]/td、//tr[1]/td、//tr[2]/td、//tr[3]/td 和所以这是不正确的。我的 webelement 值位于 //tr[2]/td.
    • 如果你需要一个特定的元素,就像你说的//tr[2]/td,那么在这里使用for循环是什么意思?你能更新我吗。因为对我来说 if 在这里使用 for 循环没有任何意义。
    • 确保你在问什么,你想做什么,这两个术语应该很清楚,下次请用正确的 html 详细信息或网站 url 以及你正确的尝试过的代码提出问题。跨度>
    猜你喜欢
    • 2021-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-31
    • 1970-01-01
    • 1970-01-01
    • 2011-02-10
    相关资源
    最近更新 更多