有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

使用Selenium Java获取子项的XPath

在第三步中,我在尝试从菜单中单击子项时遇到问题

  1. 我确实登录了

  2. 参与一个项目

  3. 仅删除已创建的卡 我认为问题在于如何获得正确的xpath 页面

    包页面对象
    导入组织。openqa。硒。通过 导入组织。openqa。硒。钥匙; 导入组织。openqa。硒。网络驱动程序; 导入组织。openqa。硒。网络元素; 导入组织。openqa。硒。互动。行动
    公共类页面{ 受保护的最终WebDriver WebDriver

    public Page( final WebDriver driver ) {
        this.webDriver =driver;
    }
    
    protected WebElement element(By by ) {
        return webDriver.findElement( by );
    }
    
    public void pressEnter(){
        Actions builder = new Actions(webDriver);
        builder.sendKeys(Keys.RETURN).perform();
    }
    

    }

页面对象:卡片页面

package Helpers;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.interactions.Actions;
public class public class CardPage extends PageObject.Page{

    By close = By.xpath("//*[@id='ngdialog5']/div[2]/div/div[2]");
    By menuCard = By.xpath("html/body/div[1]/div/div/div/div/ui-view/project/div[1]/board/div/div/div/backlog-list/div[2]/div/ul/li/ul/div[1]/card/li/div/div[1]/a[3]");
    By container1stCard = By.xpath("html/body/div[1]/div/div/div/div/ui-view/project/div[1]/board/div/div/div/backlog-list/div[2]/div/ul/li/ul/div/card/li/div");
    By delete3 = By.xpath("//*[contains(text(), 'delete')]");

    By accceptWarning = By.xpath("html/body/div[4]/div/div[10]/button[1]");
    By openCard = By.xpath("//*[@id=\"scrollable\"]/div/backlog-list/div[2]/div/ul/li/ul/div/card/li/div");

    private Services services;
    public CardPage(WebDriver driver) {
        super(driver);
    }
    //SERVICES CARDS
    private void closeCard() {
        element(close).click();
    }
    public void delete1stCard(){
        WebElement Wcontainer1stCard = element(container1stCard);//Menu
        Actions builder = new Actions(super.webDriver);
        Actions hoverOverContainer = builder.moveToElement(Wcontainer1stCard);
        hoverOverContainer.perform();
        Services.waitMilisegundos(1000);
        element(menuCard).click();

        Services.waitMilisegundos(500);
        WebElement deleteBtn = element(delete3);
        deleteBtn.click();//Menu Item
        Services.waitMilisegundos(1000);
    }
    public void openCard(){
        element(openCard).click();
    }
}

页面对象的服务

package Helpers;

import PageObject.*;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.*;
import org.openqa.selenium.interactions.Actions;

import java.io.File;
import java.io.IOException;
import java.util.Date;

public class Services {
    WebDriver webDriver;
    private LandingPage landingPage;
    private MainPage mainPage;
    private LoginPage loginPage;
    private ProjectPage projectPage;
    private CardPage cardPage;
    String url;
    ////
    public Services(TmpEnvironment environment) {
        webDriver = new StartDriver( environment.url ).getWebDriver();
    }
    public Services() {
        webDriver = new StartDriver(TmpEnvironment.STAGING).getWebDriver();
    }

    ///LOGIN SERVICES
    public Services login(String email, String passw){
        getLandingPage().goToLoginPage();
        getLoginPage().writeUserName(email)
                .writePassword(passw)
                .clickOnLogin();
        return this;
    }
    public Services enterToProject() {
        getMainPage().enterToProject();
        return this;
    }
    //PAGES GETTERS
    public WebDriver getWebDriver() {
        return webDriver;
    }
    public MainPage getMainPage() {
        if (mainPage == null)
            mainPage = new MainPage(webDriver);
        return mainPage;
    }
    public LoginPage getLoginPage() {
        if (loginPage == null)
            loginPage = new LoginPage(webDriver);
        return loginPage;
    }
    public ProjectPage getProjectPage(){
        if (projectPage == null)
            projectPage = new  ProjectPage(webDriver);
        return projectPage;
    }
    public LandingPage getLandingPage() {
        if (landingPage == null)
            landingPage =  new LandingPage(webDriver);
        return landingPage;
    }
    public CardPage getCardPage() {
        if (cardPage == null)
            cardPage = new CardPage(webDriver);
        return cardPage;
    }
    //CARDS SERVICES
    public Services delete1stCard() {
        getCardPage().delete1stCard();
        return this;
    }
    public static void waitMilisegundos(){
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    public void pressEnter(){
        Actions builder = new Actions(webDriver);
        builder.sendKeys(Keys.RETURN).perform();
    }
    public void pressEsc(){
        Actions builder = new Actions(webDriver);
        builder.sendKeys(Keys.ESCAPE).perform();
    }
    //
    public Services goToLoginPage() {
        getLandingPage().goToLoginPage();
        return this;
    }

    public enum TmpEnvironment {
        DEVELOPMENT( "http://tmp-landing-dev.theamalgama.com/index" ),
        STAGING( "https://tmpapp.theamalgama.com" ),
        PRODUCTION( "https://tmpapp.com" );
        public final String url;
        TmpEnvironment( final String url ) {
            this.url = url;
        }
        public String getUrl(){
            return url;
        }
    }
}

考试班

package z_Test;

import Helpers.Services;
import org.junit.After;
import org.junit.BeforeClass;
import org.junit.Test;

import static Helpers.Services.waitMilisegundos;

public class CardTest {
    static String email, password;
    Services services;

    public CardTest(){
        services = new Services();
    }
    @BeforeClass
    public static void setData(){
        email = "test01@testing.com";
        password = "password";

    }
    @After
    public void CloseDriver(){
        services.getWebDriver().close();
    }


    /////////////////////////////////////////////////////////////
    @Test
    public void cardTest(){ 
        services.login(email,password);
        services.enterToProject()
        .delete1stCard();
        waitMilisegundos();
    }
}

下一步是尝试删除卡时的错误消息

[org.openqa.selenium.ElementNotVisibleException: element not visible
(Session info: chrome=58.0.3029.110) (Driver info: chromedriver=2.30.477691 (6ee44a7247c639c0703f291d320bdf05c1531b57),platform=Linux 4.4.0-79-generic x86_64) (WARNING: The server did not provide any stacktrace information) Command duration or timeout: 96 milliseconds Build info: version: 'unknown', revision: 'unknown', time: 'unknown' System info: host: 'julieta', ip: '127.0.1.1', os.name: 'Linux', os.arch: 'amd64', os.version: '4.4.0-79-generic', java.version: '1.8.0_131' Driver info: org.openqa.selenium.chrome.ChromeDriver Capabilities [{applicationCacheEnabled=false, rotatable=false, mobileEmulationEnabled=false, networkConnectionEnabled=false, chrome={chromedriverVersion=2.30.477691 (6ee44a7247c639c0703f291d320bdf05c1531b57), userDataDir=/tmp/.org.chromium.Chromium.rQuYOu}, takesHeapSnapshot=true, pageLoadStrategy=normal, databaseEnabled=false, handlesAlerts=true, hasTouchScreen=false, version=58.0.3029.110, platform=LINUX, browserConnectionEnabled=false, nativeEvents=true, acceptSslCerts=true, locationContextEnabled=true, webStorageEnabled=true, browserName=chrome, takesScreenshot=true, javascriptEnabled=true, cssSelectorsEnabled=true, unexpectedAlertBehaviour=}] Session ID: a33c710a9bae046f731a66bb56b344b8 at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) at java.lang.reflect.Constructor.newInstance(Constructor.java:423) at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:215) at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:167) at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:671) at org.openqa.selenium.remote.RemoteWebElement.execute(RemoteWebElement.java:272) at org.openqa.selenium.remote.RemoteWebElement.click(RemoteWebElement.java:82) at PageObject.CardPage.delete1stCard(CardPage.java:92) at Helpers.Services.delete1stCard(Services.java:201) at z_Test.CardTest.cardTest(CardTest.java:69) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50) at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47) at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17) at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27) at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325) at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78) at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57) at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290) at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71) at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58) at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268) at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26) at org.junit.runners.ParentRunner.run(ParentRunner.java:363) at org.junit.runner.JUnitCore.run(JUnitCore.java:137) at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68) at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47) at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242) at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)

]

我还尝试使用不同的xpath,所以运行它时,我得到了另一种解释:org.openqa.selenium.NoSuchElementException: Unable to locate element:


共 (1) 个答案

  1. # 1 楼答案

    我认为你有很多问题需要改进

    1. 你使用的是绝对的XPath,这是一个糟糕的做法。它们非常脆弱。你应该花些时间阅读一些手工制作XPath的教程。它们会更短,更容易阅读,但也不会那么脆弱

    2. 不要使用delete1stCard()方法,而是创建一个deleteCard(int index)方法,该方法采用索引,这样你就可以删除任何你想要的卡片。您可能需要另一种方法deleteCard(String cardName),它接收卡名并将其删除。我认为这可能比按索引删除更有用,但我不知道您的测试用例是什么样子。(或者更好的方法是实现一个卡片组件类,正如我在下面建议的那样,它解决了这个问题。)

    3. 你叫Services的班级似乎是一个包罗万象的人。做一个合适的页面对象模型,添加一个处理登录页面登录的登录页面,一个处理该页面的项目页面,等等。我不知道一旦你把所有东西重新组织成一个合适的页面对象Services应该包含什么内容。。。我认为你可能不需要它

    4. 我还建议您创建组件页面对象,例如卡片和一些工具栏。“页面对象”不一定是整个页面。它可以是任何可重用的组件。您可以获取Services类中可用的一些函数,并将它们移动到TimerMenuProjectBar等组件中,以表示页面顶部的不同工具栏及其函数

    5. 你会有一个CardsPage页面对象来表示卡片页面,例如https://tmpapp.theamalgama.com/#/projects/681/cards,但你也会有一个CardComponent来表示页面上的一张实际卡片,即包含在<card>标记中的内容。该CardComponent将包含单卡的功能。。。姓名、该卡的播放按钮、该卡的完成图标、该卡的删除/编辑/etc选项,等等

    现在来看看真正的答案。正如我建议你写的那样,我写了一个CardComponent类。你输入卡片的名字,它就会得到一个句柄。从那里,你可以直接调用card.delete()card.whatever(),这个操作将在你指定的卡上完成。它使处理个人卡片、项目等变得更加容易。更新卡的功能很容易。。。在CardComponent页面对象中进行更改,等等

    public class CardComponent
    {
        private WebDriver driver;
        private WebElement card;
        private By deleteCardLocator = By.xpath(".//p[@class='option-list-option'][.='Delete']");
        private By acceptDeleteButtonLocator = By.xpath("//button[.='Accept']");
    
        public CardComponent(WebDriver webDriver, String cardName)
        {
            driver = webDriver;
            card = new WebDriverWait(webDriver, 10)
                    .until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//card[contains(., '" + cardName + "')]")));
        }
    
        public void delete()
        {
            openMenu();
            card.findElement(deleteCardLocator).click();
            driver.findElement(acceptDeleteButtonLocator).click();
        }
    
        private void openMenu()
        {
            new Actions(driver).moveToElement(card).perform();
            card.findElement(By.id("dots")).click();
        }
    }
    

    要使用此代码,请导航到cards页面并调用

    CardComponent card = new CardComponent(driver, "card to delete");
    card.delete();
    

    我创建了两张新卡,并测试了这段代码,它运行正常