我应该如何通过页面对象模型使用 WebElements 和 Actions?

How should I use WebElements and Actions through page object model?

我的网页上有一个按钮,我想在输入所需信息后单击该按钮。我目前正在使用 By 来建立页面的所有元素,但想为该按钮使用 WebElements,然后使用 Actions 稍后单击它。 我应该如何在我的页面对象中做到这一点 class。

我尝试了以下方法:

WebElement addressinput = driver.findElement(By.xpath("//input[@id='pac-input']"));
By addressinput = By.xpath("//input[@id='pac-input']");//this works fine

但是在 运行 作为 TestNG 的测试 class 上,它在 WebElement 行上显示空指针异常。也尝试用 By 来做,但按钮只是不会收到点击。它与 WebElements 完美配合,我之前在不使用 POM 的情况下尝试过的操作下面是参考代码:

WebElement button = driver.findElement(By.xpath("//button[@id='btn_gtservice']"));  
Actions action = new Actions(driver);
action.moveToElement((WebElement) CheckAvailability).click().perform();
driver.switchTo().defaultContent();

你有

action.moveToElement((WebElement)CheckAvailability)

应该是

action.moveToElement((button)CheckAvailability)

事实上,您将得到一个空指针,因为您没有定义名为 WebElement 的变量

PageObjectModel 中使用 PageFactory 时,如果您希望在输入一些信息后加载元素,通过一些 JavaScript 并且它可能不会立即出现在页面上,您可以使用 Actions 一旦通过 WebDriverWait 支持返回元素并使用普通定位器工厂如下:

  • 代码块:

    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;
    import org.openqa.selenium.interactions.Actions;
    
    public class ZohoLoginPage {
    
        WebDriver driver;
        public ZohoLoginPage(WebDriver driver)
        {
            PageFactory.initElements(driver, this);
        }
    
        @FindBy(xpath="//button[@id='btn_gtservice']")
        public WebElement myButton;
    
        public void doLogin(String username,String userpassword)
        {
            WebElement button = new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(ZohoLoginPage.getWebElement()));
            new Actions(driver).moveToElement(button).click().perform();
        }
    
        public WebElement getWebElement()
        {
            return myButton;
        }
    
    }
    

您可以在 How to use explicit waits with PageFactory fields and the PageObject pattern

中找到详细的讨论