我在下面的代码中添加了硬代码等待thread.sleep()
。如何使用显式等待。我想等到“用户名” WebElement出现。我的程序运行正常。我已经写了测试用例。
package com.pol.zoho.PageObjects;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import org.openqa.selenium.support.ui.WebDriverWait;
public class ZohoLoginPage {
WebDriver driver;
public ZohoLoginPage(WebDriver driver)
{
PageFactory.initElements(driver, this);
}
@FindBy(xpath=".//*[@id='lid']")
public WebElement email;
@FindBy(xpath=".//*[@id='pwd']")
public WebElement password;
@FindBy(xpath="//*[@id='signin_submit']")
public WebElement signin;
public void doLogin(String username,String userpassword)
{
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
email.sendKeys(username);
password.sendKeys(userpassword);
signin.click();
}
}
答案 0 :(得分:1)
您有两个选择:
1-您可以在初始化驱动程序时使用隐式等待。
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
2-使用显式仅等待用户名字段:
WebDriverWait wait = new WebDriverWait(driver,30);
WebElement element = wait.until(
ExpectedConditions.visibilityOf(By.id(identifier)));
答案 1 :(得分:1)
在 PageObjectModel 中使用 PageFactory 时,如果您希望元素通过某些JavaScript加载,并且该元素可能不存在于页面上,则可以使用普通定位器工厂的 Explicit Wait 支持如下:
代码块:
package com.pol.zoho.PageObjects;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import org.openqa.selenium.support.ui.WebDriverWait;
public class ZohoLoginPage {
WebDriver driver;
public ZohoLoginPage(WebDriver driver)
{
PageFactory.initElements(driver, this);
}
@FindBy(xpath=".//*[@id='lid']")
public WebElement email;
@FindBy(xpath=".//*[@id='pwd']")
public WebElement password;
@FindBy(xpath="//*[@id='signin_submit']")
public WebElement signin;
public void doLogin(String username,String userpassword)
{
WebElement element = new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(ZohoLoginPage.getWebElement()));
email.sendKeys(username);
password.sendKeys(userpassword);
signin.click();
}
public WebElement getWebElement()
{
return email;
}
}
您可以在How to use explicit waits with PageFactory fields and the PageObject pattern
中找到详细的讨论