尽管没有使用或调用 WebElement,Selenium 没有这样的元素异常

Selenium No such element exception despite not using or calling the WebElement

现在我正在执行一个测试用例,但我得到了一个 NoSuchElementException,尽管我的测试用例中没有使用该元素。这是我的实现。

这是我的页面图层


    public class NotificationsPage extends BasePage {
    
        private final WebElement datePicker = 
                driver.findElement(By.xpath("(//input[@aria-label='Password2'])[1]"));
        public String textBoxData = "";
        public String date1 = "";
        public String date2 = "";
        private final WebElement notificationTitle = driver.findElement(By.xpath("//a[@class='pmd-list-title']"));
        
        {
            textBoxData = datePicker.getAttribute("value");
            String[] parts = textBoxData.split("-");
            date1 = parts[0].trim();
            date2 = parts[1].trim();
        }
        
        public String getNotificationTitle()
        {
            String title = notificationTitle.getText();
            return title;
        }
    }

这是我正在执行的测试用例


    @Test
        public void testDateSettings(Map<String, String> map) throws Exception
        {
            try
            {
                new LoginPage().clickLoginButton().setUserName(map.get("username")).setPassword(map.get("password")).clickSubmit()
                .clickHighlights();
            }
            catch(ExceptionInInitializerError ex)
            {
                ex.printStackTrace();
            }
            
            NotificationsPage notificationsPage = new NotificationsPage();
            String systemDate = DateTimeUtils.getSystemDate();
            System.out.println("System date:: "+systemDate);
            System.out.println("Date1:: "+notificationsPage.date1);
            System.out.println("Date2:: "+notificationsPage.date2);
            Assertions.assertThat(systemDate).isBetween(notificationsPage.date1, notificationsPage.date2);
        }

现在如您所见,我没有在这个特定的测试用例中使用元素 notificationTitle,但它仍然为我提供该 WebElement 的 NoSuchElementException。这是堆栈跟踪

org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":"//a[@class='pmd-list-title']"}
  (Session info: chrome=94.0.4606.81)
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-R3JT7MO', ip: '192.168.0.103', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '16.0.1'
Driver info: org.openqa.selenium.chrome.ChromeDriver
Capabilities {acceptInsecureCerts: false, browserName: chrome, browserVersion: 94.0.4606.81, chrome: {chromedriverVersion: 94.0.4606.61 (418b78f5838ed..., userDataDir: C:\Users\CHINMA~1\AppData\L...}, goog:chromeOptions: {debuggerAddress: localhost:65399}, 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, webauthn:extension:credBlob: true, webauthn:extension:largeBlob: true, webauthn:virtualAuthenticators: true}
Session ID: b059694161fd932a928a64dc2c56d31d
*** Element info: {Using=xpath, value=//a[@class='pmd-list-title']}
    at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:78)
    at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.base/java.lang.reflect.Constructor.newInstanceWithCaller(Constructor.java:499)
    at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:480)
    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 com.digicorp.pageobjects.NotificationsPage.<init>(NotificationsPage.java:15)
    at com.digicorp.pageobjects.HomePage.clickHighlights(HomePage.java:77)
    at com.digicorp.testcases.TC_HighlightsSection.testDateSettings(TC_HighlightsSection.java:37)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:78)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:567)
    at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:133)
    at org.testng.internal.TestInvoker.invokeMethod(TestInvoker.java:598)
    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:824)
    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:1511)
    at org.testng.TestRunner.privateRun(TestRunner.java:794)
    at org.testng.TestRunner.run(TestRunner.java:596)
    at org.testng.SuiteRunner.runTest(SuiteRunner.java:377)
    at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:371)
    at org.testng.SuiteRunner.privateRun(SuiteRunner.java:332)
    at org.testng.SuiteRunner.run(SuiteRunner.java:276)
    at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:53)
    at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:96)
    at org.testng.TestNG.runSuitesSequentially(TestNG.java:1212)
    at org.testng.TestNG.runSuitesLocally(TestNG.java:1134)
    at org.testng.TestNG.runSuites(TestNG.java:1063)
    at org.testng.TestNG.run(TestNG.java:1031)
    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)

谁能告诉我我哪里出错了。

你不应该这样声明,

private final WebElement notificationTitle = driver.findElement(By.xpath("//a[@class='pmd-list-title']"));

每当 class 正在初始化时,驱动程序将开始查找此元素,然后导致 NoSuchElementException

声明 by 并在需要的任何地方调用它,

private final By notificationTitleTxt = By.xpath("//a[@class='pmd-list-title']");

像你的方法一样调用它,

driver.findElement(notificationTitleTxt).getText();

我在这里要做的是

  1. 使用try-catch

  2. 使用 findElements

findElements

的示例代码
private final List<WebElement> notificationTitle = driver.findElements(By.xpath("//a[@class='pmd-list-title']"));

并在您的实例中初始化

public String getNotificationTitle()
{
    String title = notificationTitle.get(0).getText();
    return title;
}

或者为什么不简单地尝试捕获块?

try {
     private final WebElement notificationTitle = 
       driver.findElement(By.xpath("//a[@class='pmd-list-title']"));
   }
   catch(ExceptionInInitializerError ex){
       ex.printStackTrace();
   }