如何通过页面对象模型使用WebElements和Action?

时间:2019-01-05 09:01:55

标签: selenium selenium-webdriver action pageobjects webdriverwait

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

我尝试了以下方法:

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

但是在将Test类作为TestNG运行时,它在WebElement行上显示了空指针异常。也尝试通过“按”来执行此操作,但该按钮将无法接收该点击。它可以完美地与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();

2 个答案:

答案 0 :(得分:0)

您已经

action.moveToElement((WebElement)CheckAvailability)

应该是

action.moveToElement((button)CheckAvailability)

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

答案 1 :(得分:0)

PageObjectModel 中使用 PageFactory 时,如果您希望元素在输入某些信息后通过某些JavaScript加载,则可能不会立即显示在页面上已经可以通过 WebDriverWait 支持通过普通定位器工厂返回元素后使用 Actions ,如下所示:

  • 代码块:

    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

中找到详细的讨论