【发布时间】:2017-03-08 08:20:15
【问题描述】:
我已经编写了以下代码来登录网站"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();
}
}
【问题讨论】:
-
我取消了两次睡眠,它对我来说效果很好,根本不需要等待。不过我正在使用 Chrome 驱动程序...
-
你可以开始使用QMetry Automation Framework,它提供了扩展的webdriver和webelement,可以在内部自动处理这种情况。还有明确的等待条件,assertions, verification 可用于元素。例如,
element.waitForPresent()或element.assertPresent()或element.verifyPresent()。
标签: java selenium selenium-webdriver webdriver