如何解决Selenium中的org.openqa.selenium.NoSuchElementException?

时间:2018-08-20 04:48:20

标签: java selenium

TestBase类:-

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

    }

首页类:-

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类:-

 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类:-

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类:-

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

}

错误消息:-

**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:-

我正在尝试使用Selenium开发Hybrid Framework。我以积极的态度开始,但是在org.openqa.selenium.NoSuchElementException中停留了三天。我已经尝试了三天,但我一无所知。我在这里。

2 个答案:

答案 0 :(得分:1)

原因1:您尚未共享loginpage.login()方法的详细信息,它必须返回新的HomePage(),以便调用HomePage构造函数并初始化其元素,并准备进行任何操作要执行

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

原因2:如果我假设您正确初始化了HomePage元素,则可能存在同步问题-当您执行登录时,HomePage仍未加载,但执行movetoContact方法不会抛出此类元素错误对于下面的元素

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

修正2:在您的HomePage方法中添加等待条件,如下所述

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

注意-建议使用可加载组件类。我已经在我的github存储库 here 和官方站点链接 here 中显示了它的用法。

答案 1 :(得分:0)

当前错误与以下事实有关:定位"//a[text()='Contacts']"元素时,该元素在DOM中不可用。甚至XPath本身可能是正确的,但在访问元素时当时尚未将其加载到DOM。

我相信它会出现在这里:

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

确保您可以使用Chrome元素检查器(F12)通过XPath访问以下元素。点击Ctrl+F以显示搜索输入enter image description here