需要在没有Thread.sleep的情况下编写selenium代码

我写了以下代码登录网站“qtpselenium.com” 。

如果我在其间给出Thread.sleep以使代码执行暂停一段时间,下面的代码工作正常。 如果我评论Thread.sleep,代码不能按预期工作。 我试图使用selenium的隐式和显式等待使驱动程序等待元素可见,但代码只能在我使用Thread.sleep时按预期工作。

有没有办法,我可以使用下面的代码,而不使用Thraed.Sleep语句。

在selenium代码中使用Thread.sleep语句是不好的做法?

import java.util.concurrent.TimeUnit; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.FluentWait; public class QTPSelenium { public static WebDriver driver = null; public static void main(String[] args) throws InterruptedException { System.setProperty("webdriver.gecko.driver","C:\\Eclipse\\Drivers\\geckodriver.exe"); driver = new FirefoxDriver(); driver.get("http://qtpselenium.com/"); driver.findElement(By.xpath(".//*[@class='btn btn-default member_login']")).click(); Thread.sleep(10000); driver.findElement(By.xpath("(//button[@type='submit'])[3]")).click(); Thread.sleep(10000); driver.findElement(By.id("email")).sendKeys("Some Email ID"); driver.findElement(By.id("login-password")).sendKeys("Some Password"); driver.findElement(By.xpath("html/body/main/div[2]/div/div/div[1]/div/div/div/form/button")).click(); } } 

是的,使用Thread.sleep()通常是不好的做法。 睡眠不是动态的。 他们只等待指定的时间……不多也不少。 这通常不好,因为如果您等待的元素在25ms内返回,那么您将等待整整10s。 如果元素是10.5s,那么它将失败。 通过自动化,我们希望尽可能快地保持一致的结果。 使用WebDriverWait将允许脚本暂停并等待指定的条件。 一旦满足条件,脚本就会继续。 如果不满足,脚本将暂停指定的时间并重试,直到满足条件或发生超时(抛出exception)。 因此,请确保等待合理等待。

而是使用WebDriverWait ,如下所示。 看看ExpectedConditions 。 您可以等待许多条件……元素的存在,可点击的元素等。

我切换到geckodriver并再次尝试了代码。 我更改了定位器以使它们更具体。 他们基本上在寻找包含某些文本的标签。 您可以多次重复使用该定位器。 下面的代码对我有用。 我删除了睡眠并用WebDriverWait替换它们。

 driver.get("http://qtpselenium.com/"); driver.findElement(By.xpath("//button[contains(.,'Member Login')]")).click(); WebDriverWait wait = new WebDriverWait(driver, 5); // create a WebDriverWait that we will reuse wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//button[contains(.,'Login to Selenium Account')]"))).click(); wait.until(ExpectedConditions.presenceOfElementLocated(By.id("email"))).sendKeys("Some Email ID"); driver.findElement(By.id("login-password")).sendKeys("Some Password"); driver.findElement(By.xpath("//button[contains(.,'Login')]")).click(); 

也许试试这个而不是thread.sleep():

 driver.manage().timeouts().pageLoadTimeout(10, TimeUnit.SECONDS);