1

我在下面的代码中添加了硬代码等待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();
}

}

4

2 回答 2

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)));
于 2019-01-12T12:19:43.807 回答
1

PageObjectModel中使用PageFactory时,如果您希望元素通过一些JavaScript加载并且它可能已经不存在于页面上,您可以将显式等待支持与普通定位器工厂一起使用,如下所示:

  • 代码块:

    package com.pol.zoho.PageObjects;
    import org.openqa.selenium.By;
    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.ExpectedConditions;
    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;
        }
    
    }
    

您可以在如何使用 PageFactory 字段和 PageObject 模式使用显式等待中找到详细讨论

于 2019-01-14T07:36:24.933 回答