简体   繁体   中英

How to resolve org.openqa.selenium.NoSuchElementException in Selenium?

TestBase Class:-

 public class TestBase {

        public static WebDriver driver;
        public static Properties prop;

        // TestBase class constructor is used to initialize the properties object to
        // fetch config variables from config.properties file.
        public TestBase() {

            try {             

                File src = new File(".\\src\\main\\java\\com\\config\\config.properties");

                FileInputStream fs = new FileInputStream(src);

                prop = new Properties();

                prop.load(fs);

            } catch (Exception e) {

                e.printStackTrace();

            }
        }

        public static void initialzation() throws InterruptedException {
            String browserName = prop.getProperty("Browser");
            if (browserName.equals("chrome")) {
                System.setProperty("webdriver.chrome.driver", "C:\\Selenium\\chromedriver_win32\\chromedriver.exe");
                driver = new ChromeDriver();
            }

            else {
                System.out.println("Oops! Exception has Caught");
            }

            driver.manage().window().maximize();

            driver.get(prop.getProperty("URL"));
        }

    }

HomePage Class:-

public class HomePage extends TestBase {


    @FindBy(xpath="//a[@title='Calendar']")
    WebElement calendarLink;

    @FindBy(xpath="//a[text()='Companies']")
    WebElement companiesLink;

    @FindBy(xpath="//a[text()='Contacts']")           
    WebElement contactsLink;

    @FindBy(xpath="//a[text()='New Contact']")
    WebElement newContact; 

    @FindBy(xpath="//a[@title='Deals']")
    WebElement dealsLink;

    @FindBy(xpath="//a[text()='Tasks']")
    WebElement tasksLink;

    @FindBy(xpath="//a[text()='Cases']")
    WebElement casesLink;

    @FindBy(xpath="//a[text()='Call']")
    WebElement callLink;

    @FindBy(xpath="//a[text()='Email']")
    WebElement emailLink;

    @FindBy(xpath="//a[text()='Text/SMS']")
    WebElement text_smsLink;

    @FindBy(xpath="//a[text()='Print']")
    WebElement printLink;

    @FindBy(xpath="//a[text()='Campaigns']")
    WebElement campaignLink;

    @FindBy(xpath="//a[text()='Docs']")
    WebElement docsLink;

    @FindBy(xpath="//a[text()='Forms']")
    WebElement formLink;

    @FindBy(xpath="//a[text()='Reports']")
    WebElement reportsLink;

    //Initializing the Page Objects
    public HomePage()
    {
        PageFactory.initElements(driver, this);
    }

    public String verifyHomePageTitle() throws InterruptedException
    {   
        return driver.getTitle();
    }

    public CalendarPage clickOnCalendar() throws InterruptedException
    {   
        calendarLink.click();
        Thread.sleep(3000);
        return new CalendarPage();

    }

    public CompaniesPage clickOnCompanies() throws InterruptedException
    {

        companiesLink.click();
        Thread.sleep(3000);
        return new CompaniesPage();

    }

    public ContactsPage contactsLink() throws InterruptedException
    {   
        contactsLink.click();
        Thread.sleep(3000);
        return new ContactsPage();

    }

    public DealsLink clickOnDealsLink() throws InterruptedException
    { 
        dealsLink.click();
        Thread.sleep(3000);
        return new DealsLink();
    }

    public TasksLink clickOnTasksLink() throws InterruptedException
    {
        tasksLink.click();
        Thread.sleep(3000);
        return new TasksLink();
    }

    public ContactsPage moveToNewContact() throws InterruptedException
    {
        Actions a = new Actions(driver);
        a.moveToElement(contactsLink).build().perform();
        a.click(newContact).build().perform();
        return new ContactsPage();
    }

    public CasesLink clickOnCasesLink() throws InterruptedException
    {
        casesLink.click();
        Thread.sleep(3000);
        return new CasesLink();
    }

    public CallLink clickOnCallLink() throws InterruptedException
    {
        callLink.click();
        Thread.sleep(3000);
        return new CallLink();
    }

    public EmailLink clickOnEmailLink() throws InterruptedException
    {
        emailLink.click();
        Thread.sleep(3000);
        return new EmailLink();
    }



    public PrintLink clickOnPrintLink() throws InterruptedException
    {
        printLink.click();
        Thread.sleep(3000);
        return new PrintLink();
    }

    public CampaignLink clickOnCampaignLink() throws InterruptedException
    {
        campaignLink.click();
        Thread.sleep(3000);
        return new CampaignLink();
    }

    public DocsLink clickOnDocsLink() throws InterruptedException
    {
        docsLink.click();
        Thread.sleep(3000);
        return new DocsLink();
    }

    /*public FormsLink clickOnFormsLink()
    {
        formsLink.click();
        return new FormsLink();
    }
    */
    public ReportsLink clickOnReportsLink() throws InterruptedException
    {
        reportsLink.click();
        Thread.sleep(3000);
        return new ReportsLink();
    }




}

ContactsPage Class:-

 public class ContactsPage extends TestBase {

        @FindBy(xpath="(//td[@class='datacardtitle'])[4]")
        WebElement contactsLabel;

        @FindBy(name="title")
        WebElement title;

        @FindBy(name="first_name")
        WebElement firstName;

        @FindBy(name="surname")
        WebElement lastName;

        @FindBy(name="client_lookup")
        WebElement company;

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

        public boolean contactsLabel()
        {
            return contactsLabel.isDisplayed();
        }

        public void createNewContact(String subject, String fName, String lName, String comp )
        {
            Select s = new Select(title);
            s.selectByVisibleText("title");

            firstName.sendKeys(fName);
            lastName.sendKeys(lName);
            company.sendKeys(comp);

        }
    }

ContactsPageTest Class:-

public class ContactsPageTest extends TestBase {

    TestUtil testUtil;
    LoginPage loginpage;
    HomePage homepage;
    ContactsPage contactsPage;
    String sheetName = "Contacts";

    public ContactsPageTest() {
        super();
    }

    @BeforeMethod()
    public void setUp() throws InterruptedException {
        initialzation();
        testUtil = new TestUtil();
        loginpage = new LoginPage();
        homepage = loginpage.login(prop.getProperty("username"), prop.getProperty("password"));
        contactsPage = new ContactsPage();

    }

    /*@Test(priority = 1)
    public void contactsLabelTest() throws InterruptedException {
        testUtil.switchToFrame();
        contactsPage = homepage.contactsLink();
        Thread.sleep(3000);
        Assert.assertTrue(contactsPage.contactsLabel(), "Exception has caught!");
    }*/

    @DataProvider
    public Object[][] getCRMTestData()
    {
    Object data[][] = TestUtil.getTestData("Contacts");
    return data;
    }

    @Test(priority=2, dataProvider="getCRMTestData")
    public void createNewContactTest(String subject, String fName, String lName, String comp) throws InterruptedException
    {
     homepage.moveToNewContact();
     contactsPage.createNewContact(subject, fName, lName, comp);

    }



    @AfterMethod
    public void close() {
        driver.close();
    }

}

TestUtil Class:-

public class TestUtil extends TestBase {

    TestUtil testUtil;
    static Workbook book;
    static Sheet sheet;

    public void switchToFrame() {
        driver.switchTo().frame("mainpanel");
    }

    public static String TESTDATA_SHEET_PATH = ".\\src\\main\\java\\com\\testData\\FreeCRMTestData.xlsx";

    public static Object[][] getTestData(String sheetName) {
        FileInputStream file = null;
        try {
            file = new FileInputStream(TESTDATA_SHEET_PATH);
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            book = WorkbookFactory.create(file);
        } catch (Exception e) {
            e.printStackTrace();
        }

        sheet = book.getSheet(sheetName);
        Object[][] data = new Object[sheet.getLastRowNum()][sheet.getRow(0).getLastCellNum()];
        for (int i = 0; i < sheet.getLastRowNum(); i++) {
            for (int k = 0; k < sheet.getRow(0).getLastCellNum(); k++) {
                data[i][k] = sheet.getRow(i + 1).getCell(k).toString();
            }
        }
        return data;
    }

}

Error Message:-

**org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":"//a[text()='Contacts']"}**
  (Session info: chrome=68.0.3440.106)
  (Driver info: chromedriver=2.41.578737 (49da6702b16031c40d63e5618de03a32ff6c197e),platform=Windows NT 10.0.16299 x86_64) (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 0 milliseconds
For documentation on this error, please visit: http://seleniumhq.org/exceptions/no_such_element.html
Build info: version: '3.13.0', revision: '2f0d292', time: '2018-06-25T15:24:21.231Z'
System info: host: 'M5-L-54658NZ', ip: '10.236.188.5', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '1.8.0_181'
Driver info: org.openqa.selenium.chrome.ChromeDriver
Capabilities {acceptInsecureCerts: false, acceptSslCerts: false, applicationCacheEnabled: false, browserConnectionEnabled: false, browserName: chrome, chrome: {chromedriverVersion: 2.41.578737 (49da6702b16031..., userDataDir: C:\Users\M4468~1.LAT\AppDat...}, cssSelectorsEnabled: true, databaseEnabled: false, goog:chromeOptions: {debuggerAddress: localhost:52964}, handlesAlerts: true, hasTouchScreen: false, javascriptEnabled: true, locationContextEnabled: true, mobileEmulationEnabled: false, nativeEvents: true, networkConnectionEnabled: false, pageLoadStrategy: normal, platform: XP, platformName: XP, rotatable: false, setWindowRect: true, takesHeapSnapshot: true, takesScreenshot: true, unexpectedAlertBehaviour: , unhandledPromptBehavior: , version: 68.0.3440.106, webStorageEnabled: true}
Session ID: 4cfacb502354b9a5837c3f97b0adb25b
*** Element info: {Using=xpath, value=//a[text()='Contacts']}
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
    at java.lang.reflect.Constructor.newInstance(Unknown Source)
    at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:214)
    at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:166)
    at org.openqa.selenium.remote.http.JsonHttpResponseCodec.reconstructValue(JsonHttpResponseCodec.java:40)
    at org.openqa.selenium.remote.http.AbstractHttpResponseCodec.decode(AbstractHttpResponseCodec.java:80)
    at org.openqa.selenium.remote.http.AbstractHttpResponseCodec.decode(AbstractHttpResponseCodec.java:44)
    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:548)
    at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:322)
    at org.openqa.selenium.remote.RemoteWebDriver.findElementByXPath(RemoteWebDriver.java:424)
    at org.openqa.selenium.By$ByXPath.findElement(By.java:353)
    at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:314)
    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.$Proxy10.getCoordinates(Unknown Source)
    at org.openqa.selenium.interactions.internal.MouseAction.getActionLocation(MouseAction.java:65)
    at org.openqa.selenium.interactions.MoveMouseAction.perform(MoveMouseAction.java:43)
    at org.openqa.selenium.interactions.CompositeAction.perform(CompositeAction.java:36)
    at org.openqa.selenium.interactions.Actions$BuiltAction.perform(Actions.java:641)
    at com.pages.HomePage.moveToNewContact(HomePage.java:112)
    at com.testCases.ContactsPageTest.createNewContactTest(ContactsPageTest.java:55)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:124)
    at org.testng.internal.Invoker.invokeMethod(Invoker.java:580)
    at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:716)
    at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:988)
    at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:125)
    at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:109)
    at org.testng.TestRunner.privateRun(TestRunner.java:648)
    at org.testng.TestRunner.run(TestRunner.java:505)
    at org.testng.SuiteRunner.runTest(SuiteRunner.java:455)
    at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:450)
    at org.testng.SuiteRunner.privateRun(SuiteRunner.java:415)
    at org.testng.SuiteRunner.run(SuiteRunner.java:364)
    at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
    at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:84)
    at org.testng.TestNG.runSuitesSequentially(TestNG.java:1208)
    at org.testng.TestNG.runSuitesLocally(TestNG.java:1137)
    at org.testng.TestNG.runSuites(TestNG.java:1049)
    at org.testng.TestNG.run(TestNG.java:1017)
    at org.testng.remote.AbstractRemoteTestNG.run(AbstractRemoteTestNG.java:114)
    at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:251)
    at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:77)


Description:-

I am trying to develop Hybrid Framework by using Selenium. I started off on a positive note but I've been stuck at org.openqa.selenium.NoSuchElementException for three days. I have been trying for three days but I am clueless. So here, I am.

Cause 1: You have not shared loginpage.login() method details, it must return new HomePage() so that HomePage constructor gets called and its elements get initialized and it is ready for any operations to be performed

// Fix 1: 
public LoginPage login()
{
   // to do login code
    return new HomePage();
}   

Cause 2: If I assume you HomePage elements are initialized correctly then there may be a sync issue - when you perform login then HomePage is still not loaded but movetoContact method is executed throwing no such element error for below element

@FindBy(xpath="//a[text()='Contacts']")           
WebElement contactsLink;

Fix 2: Add wait condition in your HomePage method as mentioned below

public ContactsPage moveToNewContact() throws InterruptedException {

  // Add wait condition here like this before clicking contactsLink WebElement
  WebDriverWait wait = new WebDriverWait(driver, 15);
  wait.until(ExpectedConditions.titleContains("HomePageTitle"));

    Actions a = new Actions(driver);
    a.moveToElement(contactsLink).build().perform(); // here you trying to access contactsLink which is not available
    a.click(newContact).build().perform();
    return new ContactsPage();
}

Note - Usage of Loadable Component class is recommended . Its usage I have shown in one project in my github repo here and official site link here .

Current error is related to the fact that when you locating "//a[text()='Contacts']" element, it is not available in your DOM. It may be even that XPath itself is correct but at the time of accessing element it's just not yet loaded to the DOM.

I believe it appears here:

public ContactsPage moveToNewContact() throws InterruptedException
{
    Actions a = new Actions(driver);
    a.moveToElement(contactsLink).build().perform(); // here you trying to access contactsLink which is not available
    a.click(newContact).build().perform();
    return new ContactsPage();
}

Ensure that you have following element accessible by it's XPath using Chrome Element Inspector ( F12 ). Click Ctrl+F for showing search input在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM