首页 > 解决方案 > Selenium Webdriver (Java) - 如何解决动态文本和倒数计时器?

问题描述

我正在自动化包含计数器的注册。

所以问题是,我想注册每 7 分钟发生一次的事情。

网页代码如下所示:

<class-countdown-timer _ngcontent-c19="" _nghost-c24="">
  <!---->
  <h2 _ngcontent-c24="" id="class-countdown-timer">Próxima clase en vivo en <span _ngcontent-c24="" class="countdown-timer">02:15</span>
    <i _ngcontent-c24="" aria-hidden="true" class="icon-clock"></i>
  </h2>
</class-countdown-timer>

我的问题是“class-countdown-timer”文本是动态的,“countdown-timer”是倒计时,从 07:00 到 00:00。

我的求助是当“class-countdown-timer”文本是“Próxima clase en vivo en”并且计数器在“05:00”和“02:00”之间时,我需要执行某个操作

我无法流畅地等待,直到第一个,倒计时文本显示以上内容,计时器在这些时间之间,知道吗?

感谢:D

标签: javaseleniumselenium-webdriverwebdriverwait

解决方案


试试下面的代码:

// Count-down timer for looping upto 8 minutes
        int countdown = 480;
        while(countdown-->0) {
            // Fetching the actual class-countdown-timer value
            String actualTimerText = driver.findElement(By.id("class-countdown-timer")).getText().trim();
            String expectedTimerText = "Próxima clase en vivo en ";

            // Fetching the actual countdown-timer value
            String countdownTimer = driver.findElement(By.xpath("//span[@class='countdown-timer']")).getText().trim();

            // Converting the time for better comparing
            SimpleDateFormat format = new SimpleDateFormat("hh:mm");
            Date expectedFirstTime = format.parse("05:00"), expectedSecondTime = format.parse("02:00");
            Date actualCountdownTimer = format.parse(countdownTimer);

            // Checking the condition if the 'class-countdown-timer' text is 'Próxima clase en vivo ee' and counter is in between '05:00' and '02:00' or not? 
            if(actualTimerText.equals(expectedTimerText) && ((actualCountdownTimer.equals(expectedSecondTime) || actualCountdownTimer.after(expectedSecondTime)) && (actualCountdownTimer.equals(expectedFirstTime) || actualCountdownTimer.before(expectedFirstTime)))) {
                System.out.println("Condition Satisfied...");
                // Do something
                break;
            }
            // Waiting for one second before finding the element and checking the condition
            Thread.sleep(1000);
        }

上述方法是使用循环概念,迭代最多 8 分钟(480 秒),直到满足所需条件。


推荐阅读