【发布时间】:2021-09-17 14:27:40
【问题描述】:
我正在用 Selenium 编写一些测试,但遇到了一个烦人的问题。在我的代码中,Thread.sleep 每隔一行重复一次,因为我需要在方法中的每个函数之后短暂睡眠。如何避免。我不喜欢我的代码。它看起来非常邋遢。我想改变这个重复的 Thread.sleep 以获得更优化的东西。这是我的代码:
@Test
public void shouldDownloadDriver() throws InterruptedException{
driver.get("https://www.selenium.dev/");
driver.manage().window().maximize();
Thread.sleep(1500);
driver.findElement(By.xpath("//*[@id=\"main_navbar\"]/ul/li[4]/a/span")).click();
Thread.sleep(1500);
driver.findElement(By.xpath("//*[@id=\"m-documentationgetting_started\"]/span")).click();
Thread.sleep(1500);
driver.findElement(By.xpath("//*[@id=\"m-documentationgetting_startedinstalling_browser_drivers\"]/span")).click();
Thread.sleep(1500);
((JavascriptExecutor) driver).executeScript("window.open()");
ArrayList<String> tabs = new ArrayList<String>(driver.getWindowHandles());
driver.switchTo().window(tabs.get(1));
driver.get("https://chromedriver.storage.googleapis.com/index.html");
Thread.sleep(1500);
driver.findElement(By.xpath("/html/body/table/tbody/tr[100]/td[2]/a")).click();
Thread.sleep(1500);
driver.findElement(By.xpath("/html/body/table/tbody/tr[4]/td[2]/a")).click();
Thread.sleep(2000);
driver.switchTo().window(tabs.get(0));
Thread.sleep(3000);
printSuccess();
}
【问题讨论】:
-
可以使用WebDriverWait
Wait<WebDriver> wait = new WebDriverWait(webDriver, Duration.ofSeconds(1500); wait.until(ExpectedConditions.visibilityOf(By.xpath("//*[@id=\"main_navbar\"]/ul/li[4]/a/span")); -
发布了答案。请查看并回复。