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

时间:2016-10-26 05:20:14

标签: java selenium selenium-webdriver webdriver

我已编写以下代码登录网站"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();
    }
}

2 个答案:

答案 0 :(得分:1)

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

而是使用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();

答案 1 :(得分:0)

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

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