Я создал проект maven и в одном классе (в src / main / java) разработал PageFactory (который содержит функции). И из src / test / java я создал testNG class и пытается вызвать метод selectDepartureDate (), присутствующий в src / main / java. При выполнении программы он показывает мне ошибку «не удалось найти элемент», тогда как когда я использую тот же локатор в одной программе main (), он работает отлично. Может ли кто-нибудь помочь мне определить проблему. Сайт, который я использую, makemytrip (https://www.makemytrip.com/) и пытаюсь выбрать дату отъезда.
Ниже приведена программа в src / test / java, где я вызываю function selectDepartureDate () из validateDateSelection ().
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>