想在Selenium中创建一个计时器并执行一些操作,直到达到定义的时间段 [英] Would like to create a timer in Selenium and do some action until reach a defined period of time
问题描述
我正在尝试继续循环执行某个动作,直到达到特定时间段为止.
I'm trying to keep executing an action in a loop until reach a specific period of time.
示例:执行类似sysout的命令10秒钟,然后停止执行.
Example: execute something like sysout for 10 seconds, then stop the execution.
我已经看到了有关Timer类的一些信息,但到目前为止还没有用.
I have seen some information about Timer class but was not useful so far.
在下面的代码中,尝试使页面向下滚动(因为这是无限滚动),直到达到几秒钟的时间.
In the code below, trying the keep scrolling down (because it is a infinite scroll) the page until reach some time in seconds.
JavascriptExecutor js = (JavascriptExecutor) driver;
while(countdown <= 15) {
//countdown should be my defined limit of time
js.executeScript("window.scrollTo(0, document.body.scrollHeight);");
}
推荐答案
使用以下代码:
import java.text.ParseException;
import java.util.concurrent.TimeUnit;
public class WaitAndExecute {
public static void main(String[] args) throws InterruptedException, ParseException {
long startTime = System.nanoTime();
long endTime = startTime;
long durationInSeconds = 0;
long durationInNano = 0;
while(durationInSeconds<10) {
methodToTime();
System.out.println("2 seconds");
endTime = System.nanoTime();
durationInNano = (endTime - startTime); // Total execution time in nano seconds
durationInSeconds = TimeUnit.NANOSECONDS.toSeconds(durationInNano); // Total execution time in seconds
if(durationInSeconds>=10) {
System.out.println("10 seconds done");
break;
}
}
System.out.println(durationInSeconds);
}
private static void methodToTime() {
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
输出:
2秒2秒2秒2秒2秒2秒10秒完成10
2 seconds 2 seconds 2 seconds 2 seconds 2 seconds 10 seconds done 10
旧代码
使用以下代码:
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.JavascriptExecutor;
public class WaitAndExecute {
public static void main(String[] args) throws InterruptedException {
int countdown = 1;
while (countdown < 10){
System.out.println(countdown);
JavascriptExecutor js = (JavascriptExecutor) driver; // pass your webdriver reference variable
js.executeScript("window.scrollTo(0, document.body.scrollHeight);");
++countdown;
TimeUnit.SECONDS.sleep(10);
}
}
根据您需要的迭代更改下面的行号:
Change the below line number as per the iteration you need:
while (countdown < 10){
这篇关于想在Selenium中创建一个计时器并执行一些操作,直到达到定义的时间段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!