簡體   English   中英

無法定位元素:通過 POM 執行代碼時出錯,通過單個 main() 程序執行時相同的定位器工作正常

[英]Getting Unable to locate element: error when executing code through POM, The same locator works fine when executed through single main() program

我創建了一個 maven 項目,在一個類中(在 src/main/java 中)我設計了 PageFactory(包含函數)。從 src/test/java 中,我創建了 testNG ZA2F2ED4F8EBC04DepartureABDBB4C21A29 () 方法存在於 src/main/java 中。 在執行程序時,它向我顯示錯誤“無法定位元素”,而當我在單個 main() 程序中使用相同的定位器時,它工作得非常好。 有人可以幫我確定問題嗎。 我正在使用的網站是 makemytrip( https://www.makemytrip.com/ )並嘗試 select 出發日期。

下面是 src/test/java 中的程序,我從 validateDateSelection() 調用 function selectDepartureDate()。

package com.MMT.qa.testcases;

import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

import com.MMT.qa.base.TestBaseMMT;
import com.MMT.qa.pages.FlightsHomePageMMT;

public class FlightsHomePageMMTTest extends TestBaseMMT {
    FlightsHomePageMMT homePageMMT ;
    public String dateVal = "Sun Jun 28 2020";

    public FlightsHomePageMMTTest() {
        super();
    }

    @BeforeTest
    public void setUp() {
        initialization();
        homePageMMT = new FlightsHomePageMMT();
    }

    @Test(priority = 1)
    public void validateCitySelection() {

        homePageMMT.enterValueOfFromCity();
        homePageMMT.enterValueOfToCity();
        System.out.println("city selection successfull");
    }

    @Test(priority = 2)
    public void validateDateSelection() {
        homePageMMT.selectDepartureDate(dateVal);
        System.out.println("Date selection successful");
    }

    @AfterTest
    public void tearDown() {
        driver.quit();
    }

}

下面是 src/main/java 中定義 PageFactory 的程序

package com.MMT.qa.pages;

import java.util.List;

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

import com.MMT.qa.base.TestBaseMMT;

public class FlightsHomePageMMT extends TestBaseMMT {

    //Page Factory - OR for Home page

    @FindBy(xpath = "//input[@id = 'fromCity']")
    WebElement FromCity;

    @FindBy(xpath = "//input[@placeholder = 'From']")
    WebElement FromTextFromCity;

    @FindBy(xpath = "//input[@id = 'toCity']")
    WebElement ToCity;

    @FindBy(xpath = "//input[@placeholder = 'To']")
    WebElement FromTextToCity;

    @FindBy(xpath = "//a[contains(text(),'Search')]")
    WebElement SrchBtn;

    @FindBy(xpath = "//div[@class = 'fsw_inputBox dates inactiveWidget ']")
    WebElement DepDateSelect;

    @FindBy(xpath = "//div[@class='DayPicker-Day' and @aria-label = '\"+dateVal+\"']")
    WebElement dateElement;

    public FlightsHomePageMMT() {
        PageFactory.initElements(driver, this);
    }


    //Actions

    public void enterValueOfFromCity() {
        FromCity.click();
        FromTextFromCity.sendKeys("Mumbai");
        List <WebElement> listFrom = driver.findElements(By.xpath("//ul[@role ='listbox']//li/descendant::div[@class = 'calc60']//p[contains(text(),'Mumbai, India')]"));
        System.out.println(listFrom.size());

        for(int i = 0 ; i<listFrom.size() ; i++) {
            System.out.println(listFrom.get(i).getText());
            if(listFrom.get(i).getText().contains("Mumbai, India")) {
                listFrom.get(i).click();
                break;
            }
        }
    }

    public void enterValueOfToCity() {
        JavascriptExecutor js = (JavascriptExecutor) driver;  
        js.executeScript("arguments[0].click();",ToCity);

        driver.findElement(By.xpath("//input[@placeholder = 'To']")).sendKeys("tirupati");

        List <WebElement> listTo = driver.findElements(By.xpath("//ul[@role ='listbox']//li/descendant::div[@class = 'calc60']//p[contains(text(),'Tirupati, India')]"));
        System.out.println(listTo.size());

        for(int i = 0 ; i<listTo.size() ; i++) {
            System.out.println(listTo.get(i).getText());
            if(listTo.get(i).getText().contains("Tirupati, India")) {
                listTo.get(i).click();
                break;
            }
        }
    }

    public void selectDepartureDate(String dateVal) {
        DepDateSelect.click();
        //String dateVal = "Sun Jun 28 2020";
        //System.out.println("date clicked");
        dateElement = driver.findElement(By.xpath("//div[@class='DayPicker-Day' and @aria-label = '"+dateVal+"']"));
        selectDateByJS(driver,dateElement, dateVal);
    }

    public static void selectDateByJS(WebDriver driver,WebElement dateElement, String dateVal) {
        JavascriptExecutor js = ((JavascriptExecutor)driver);
        js.executeScript("arguments[0].click();", dateElement);
    }

}

下面是我得到的錯誤。

[RemoteTestNG] detected TestNG version 7.0.1
Starting ChromeDriver 80.0.3987.106 (f68069574609230cf9b635cd784cfb1bf81bb53a-refs/branch-heads/3987@{#882}) on port 39579
Only local connections are allowed.
Please protect ports used by ChromeDriver and related test frameworks to prevent access by malicious code.
[1589036561.334][WARNING]: This version of ChromeDriver has not been tested with Chrome version 81.
[1589036563.472][WARNING]: Timed out connecting to Chrome, retrying...
May 09, 2020 8:32:45 PM org.openqa.selenium.remote.ProtocolHandshake createSession
INFO: Detected dialect: W3C
[1589036568.052][WARNING]: Timed out connecting to Chrome, retrying...
[1589036572.590][SEVERE]: Timed out receiving message from renderer: 0.100
[1589036575.221][SEVERE]: Timed out receiving message from renderer: 0.100
[1589036576.233][SEVERE]: Timed out receiving message from renderer: 0.100
[1589036577.088][SEVERE]: Timed out receiving message from renderer: 0.100
[1589036577.195][SEVERE]: Timed out receiving message from renderer: 0.100
1
Mumbai, India
1
Tirupati, India
city selection successfull
PASSED: validateCitySelection
FAILED: validateDateSelection
org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":"//div[@class = 'fsw_inputBox dates inactiveWidget ']"}
  (Session info: chrome=81.0.4044.138)
For documentation on this error, please visit: https://www.seleniumhq.org/exceptions/no_such_element.html
Build info: version: '3.141.59', revision: 'e82be7d358', time: '2018-11-14T08:17:03'
System info: host: 'DESKTOP-1QASA0A', ip: '192.168.1.129', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '14'
Driver info: org.openqa.selenium.chrome.ChromeDriver
Capabilities {acceptInsecureCerts: false, browserName: chrome, browserVersion: 81.0.4044.138, chrome: {chromedriverVersion: 80.0.3987.106 (f68069574609..., userDataDir: C:\Users\Ravindra\AppData\L...}, goog:chromeOptions: {debuggerAddress: localhost:60874}, javascriptEnabled: true, networkConnectionEnabled: false, pageLoadStrategy: normal, platform: WINDOWS, platformName: WINDOWS, proxy: Proxy(), setWindowRect: true, strictFileInteractability: false, timeouts: {implicit: 0, pageLoad: 300000, script: 30000}, unhandledPromptBehavior: dismiss and notify}
Session ID: 5f8863f488b2de8092949619e9d75e0b
*** Element info: {Using=xpath, value=//div[@class = 'fsw_inputBox dates inactiveWidget ']}
    at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.base/java.lang.reflect.Constructor.newInstanceWithCaller(Constructor.java:500)
    at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:481)
    at org.openqa.selenium.remote.http.W3CHttpResponseCodec.createException(W3CHttpResponseCodec.java:187)
    at org.openqa.selenium.remote.http.W3CHttpResponseCodec.decode(W3CHttpResponseCodec.java:122)
    at org.openqa.selenium.remote.http.W3CHttpResponseCodec.decode(W3CHttpResponseCodec.java:49)
    at org.openqa.selenium.remote.HttpCommandExecutor.execute(HttpCommandExecutor.java:158)
    at org.openqa.selenium.remote.service.DriverCommandExecutor.execute(DriverCommandExecutor.java:83)
    at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:552)
    at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:323)
    at org.openqa.selenium.remote.RemoteWebDriver.findElementByXPath(RemoteWebDriver.java:428)
    at org.openqa.selenium.By$ByXPath.findElement(By.java:353)
    at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:315)
    at org.openqa.selenium.support.pagefactory.DefaultElementLocator.findElement(DefaultElementLocator.java:69)
    at org.openqa.selenium.support.pagefactory.internal.LocatingElementHandler.invoke(LocatingElementHandler.java:38)
    at com.sun.proxy.$Proxy12.click(Unknown Source)
    at com.MMT.qa.pages.FlightsHomePageMMT.selectDepartureDate(FlightsHomePageMMT.java:80)
    at com.MMT.qa.testcases.FlightsHomePageMMTTest.validateDateSelection(FlightsHomePageMMTTest.java:34)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:564)
    at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:134)
    at org.testng.internal.TestInvoker.invokeMethod(TestInvoker.java:597)
    at org.testng.internal.TestInvoker.invokeTestMethod(TestInvoker.java:173)
    at org.testng.internal.MethodRunner.runInSequence(MethodRunner.java:46)
    at org.testng.internal.TestInvoker$MethodInvocationAgent.invoke(TestInvoker.java:816)
    at org.testng.internal.TestInvoker.invokeTestMethods(TestInvoker.java:146)
    at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:146)
    at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:128)
    at java.base/java.util.ArrayList.forEach(ArrayList.java:1510)
    at org.testng.TestRunner.privateRun(TestRunner.java:766)
    at org.testng.TestRunner.run(TestRunner.java:587)
    at org.testng.SuiteRunner.runTest(SuiteRunner.java:384)
    at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:378)
    at org.testng.SuiteRunner.privateRun(SuiteRunner.java:337)
    at org.testng.SuiteRunner.run(SuiteRunner.java:286)
    at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:53)
    at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:96)
    at org.testng.TestNG.runSuitesSequentially(TestNG.java:1187)
    at org.testng.TestNG.runSuitesLocally(TestNG.java:1109)
    at org.testng.TestNG.runSuites(TestNG.java:1039)
    at org.testng.TestNG.run(TestNG.java:1007)
    at org.testng.remote.AbstractRemoteTestNG.run(AbstractRemoteTestNG.java:115)
    at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:251)
    at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:77)


===============================================
    Default test
    Tests run: 2, Failures: 1, Skips: 0
===============================================


===============================================
Default suite
Total tests run: 2, Passes: 1, Failures: 1, Skips: 0
===============================================

下面是定位器的 HTML dom。

 <div class="fsw_inputBox dates inactiveWidget "><label for="departure"><span class="lbl_input latoBold appendBottom10">DEPARTURE</span><input data-cy="departure" id="departure" type="text" class="fsw_inputField font20" readonly="" value="Friday, 19 Jun 2020"><p data-cy="departureDate" class="blackText font20 code"><span class="font30 latoBlack ">19 </span><span>Jun</span><span class="shortYear">20</span></p><p data-cy="departureDay" class="code">Friday</p></label></div>

我已經得到了上述問題的解決方案。 代碼絕對沒問題。 我唯一缺少的是,當我們 select 時,“從”和“到城市”,然后“出發”日歷列自動打開,無需單擊“出發”的定位器。 這就是它給出 UnableToLocateElement 異常的原因。 在上面的程序中,我只刪除了該行

DepDateSelect.click();

從 function

selectDepartureDate(String dateVal) 並開始選擇日期。

以下是更新后的代碼:

public void selectDepartureDate() {
        //DepDateSelect.click();
         String dateVal = "Tue Jun 02 2020";
        try {
         WebElement element = driver.findElement(By.xpath("//div[@class='DayPicker-Day' and @aria-label = '"+dateVal+"']"));
         selectDateByJS(driver,element);
        }catch(NoSuchElementException e) {
            System.out.println("Date selected by JS");
        }

        }
     public static void selectDateByJS(WebDriver driver,WebElement element) {

            JavascriptExecutor js = ((JavascriptExecutor)driver);
            js.executeScript("arguments[0].click();", element);
        }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM