在 Selenium WebDriver 测试中使用 Page 对象时定义 Xpath 时出现问题

Having issues defining Xpath while using Page object in Selenium WebDriver testing

这里是 Selenium 新手...我正在尝试创建我的第一个测试框架。

测试网站:https://www.phptravels.net/

测试用例:

  1. 打开浏览器进入网页
  2. 页面加载后,单击“我的帐户”->“登录”

我在我的页面对象中使用了 xpath class 并且脚本 运行 只会在启动网页之前使用。单击登录失败 link .

我已经尝试包含一个隐式等待,假设页面加载所花费的时间比平时长。即便如此,问题仍然存在。

你能帮我理解什么是正确的 xpath 吗?

代码:

POM_HomePage.java

package PageObjects;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;

public class POM_HomePage {

    WebDriver driver;

    public POM_HomePage(WebDriver driver) {
        this.driver=driver;
        PageFactory.initElements(driver, this);
    }



    @FindBy(xpath="//*[@id='li_myaccount']/ul/li[1]/a")
    WebElement LinkMyAccount;
    public WebElement clickMyAccount() {
        return LinkMyAccount;
    }


}

HomePage.java

package TestGroupID;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import org.testng.annotations.Test;

import PageObjects.POM_HomePage;
import Resources.MasterScript;


public class HomePage extends MasterScript{

    @Test
    public void SignIn() throws IOException {
        driver=LoadBrowser();
        LoadPropFile();
        driver.get(prop.getProperty("test_website"));
        POM_HomePage pomHome=new POM_HomePage(driver);
        driver.manage().timeouts().implicitlyWait(60,TimeUnit.SECONDS);
        if (pomHome.clickMyAccount().isDisplayed()) {
            pomHome.clickMyAccount().click();
            driver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS);
        }
    }
}

根据您提到的问题页面加载后 单击“我的帐户”->“登录”。所以您应该在两个单独的 WebElements 上调用 click() 方法。但是你的POM_HomePage.javareturns只有一个WebElementas@FindBy(xpath="//*[@id='li_myaccount']/ul/li[1]/a")

解决方案

  • POM_HomePage.java中定义两个WebElements和两个关联的functions()如下:

    • 我的账户Link

      @FindBy(xpath="//div[@class='navbar']//li[@id='li_myaccount']/a")
      WebElement LinkMyAccount;
      public WebElement clickMyAccount() {
          return LinkMyAccount;
      }
      
    • 登录Link

      @FindBy(xpath="//div[@class='navbar']//li[@id='li_myaccount']//ul[@class='dropdown-menu']/li/a[contains(.,'Login')]")
      WebElement LinkLogin;
      public WebElement clickLogin() {
          return LinkLogin;
      }
      
  • HomePage.java 中为 WebElements 调用 isDisplayed()click(),如下所示:

    @Test
    public void SignIn() throws IOException {
        driver=LoadBrowser();
        LoadPropFile();
        driver.get(prop.getProperty("test_website"));
        POM_HomePage pomHome=new POM_HomePage(driver);
        driver.manage().timeouts().implicitlyWait(60,TimeUnit.SECONDS);
        if (pomHome.clickMyAccount().isDisplayed()) {
                pomHome.clickMyAccount().click();
        }
        if (pomHome.clickLogin().isDisplayed()) {
            pomHome.clickLogin().click();
        }
    }