gpt4 book ai didi

java - 无法定位元素 : error when executing code through POM, 通过单个 main() 程序执行时,相同的定位器工作正常

转载 作者:行者123 更新时间:2023-12-01 16:50:35 24 4
gpt4 key购买 nike

我创建了一个 Maven 项目,并在一个类(在 src/main/java 中)中设计了 PageFactory(其中包含函数)。并且从 src/test/java 中,我创建了 testNG 类并尝试调用 src/main/java 中的 selectDepartureDate() 方法。在执行程序时,它向我显示错误“无法定位元素”,而当我在单个 main() 程序中使用相同的定位器时,它工作得很好。有人可以帮我找出问题所在吗?我正在使用的网站是 makemytrip( https://www.makemytrip.com/ ) 并尝试选择出发日期。

下面是 src/test/java 中的程序,我在其中从 validateDateSelection() 调用函数 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>

最佳答案

我已经找到了上述问题的答案。代码绝对没问题。我唯一缺少的是,当我们选择“出发地”和“目的地城市”时,“出发地”日历列会自动打开,无需单击该“出发地”的定位器。这就是它给出 UnableToLocateElement 异常的原因。在上面的程序中我只删除了行

DepDateSelect.click();

来自函数

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);
}

关于java - 无法定位元素 : error when executing code through POM, 通过单个 main() 程序执行时,相同的定位器工作正常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61699126/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com