在使用Selenium Webdriver查找表时获取java.lang.NullPointerException

时间:2016-11-29 14:37:33

标签: selenium selenium-webdriver

我是Selenium Webdriver的新手。在尝试查找表中存在的行时,我收到Null Pointer异常。有人可以帮我解决这个问题吗?请找到我正在使用的以下场景和代码。 网址:http://newtours.demoaut.com/ 场景:单击页面左侧表中的每个链接。就在Mercury Tours图像之下。 这是我正在使用的代码,

public class HomePage {
    private WebDriver driver = null;

    public HomePage(WebDriver driver){
        this.driver = driver;
    }

    public void VerifyTableLink() throws InterruptedException{
        List<WebElement> rowObj = driver.findElements(By.xpath("//td[p[img[@alt='Mercury Tours']]]/table/tbody/tr"));
        System.out.println("testttt");
        for(int i=0;i<rowObj.size();i++){
            WebElement we = driver.findElement(By.xpath("//td[p[img[@alt='Mercury Tours']]]/table/tbody/tr["+i+"]/td[2]/a"));
            we.click();
            Thread.sleep(5);
            driver.navigate().back();
            String text = we.getText();
            System.out.println(text);
        }


    }

}


public class VerifyNavigationTable {
    WebDriver driver = null;

    @Parameters({"bname","appurl"})
    @BeforeMethod
    public void preCondition(@Optional("Chrome")String brow, @Optional("http://newtours.demoaut.com/")String url){
        driver = BrowserSelection.getBrowser(brow);
        BrowserSelection.openURL(url);

    }

    @Test
    public void verifyTableLink() throws InterruptedException{
        HomePage hp = new HomePage(driver);
        hp.VerifyTableLink();
    }

}

异常消息:

[Utils]   Directory D:\My Selenium Training\Practical\SeleniumLearning\SeleniumPractice4\test-output\Default suite exists: true
FAILED: verifyTableLink
org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":"//td[p[img[@alt='Mercury Tours']]]/table/tbody/tr[0]/td[2]/a"}
  (Session info: chrome=54.0.2840.99)
  (Driver info: chromedriver=2.24.417431 (9aea000394714d2fbb20850021f6204f2256b9cf),platform=Windows NT 6.2.9200 x86_64) (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 10.07 seconds
For documentation on this error, please visit: http://seleniumhq.org/exceptions/no_such_element.html
Build info: version: 'unknown', revision: '1969d75', time: '2016-10-18 09:43:45 -0700'
System info: host: 'Bishnu', ip: '192.168.0.107', os.name: 'Windows 8', os.arch: 'amd64', os.version: '6.2', java.version: '1.8.0_111'
Driver info: org.openqa.selenium.chrome.ChromeDriver
Capabilities [{applicationCacheEnabled=false, rotatable=false, mobileEmulationEnabled=false, networkConnectionEnabled=false, chrome={chromedriverVersion=2.24.417431 (9aea000394714d2fbb20850021f6204f2256b9cf), userDataDir=C:\Users\Bishnu\AppData\Local\Temp\scoped_dir10480_1335}, takesHeapSnapshot=true, pageLoadStrategy=normal, databaseEnabled=false, handlesAlerts=true, hasTouchScreen=false, version=54.0.2840.99, platform=WIN8, browserConnectionEnabled=false, nativeEvents=true, acceptSslCerts=true, locationContextEnabled=true, webStorageEnabled=true, browserName=chrome, takesScreenshot=true, javascriptEnabled=true, cssSelectorsEnabled=true}]
Session ID: c1401a5ed7966a2f15d6570c612b2449
*** Element info: {Using=xpath, value=//td[p[img[@alt='Mercury Tours']]]/table/tbody/tr[0]/td[2]/a}
    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:216)
    at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:168)
    at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:635)
    at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:368)
    at org.openqa.selenium.remote.RemoteWebDriver.findElementByXPath(RemoteWebDriver.java:473)
    at org.openqa.selenium.By$ByXPath.findElement(By.java:361)
    at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:360)
    at in.prolearn.newtours.pages.HomePage.VerifyTableLink(HomePage.java:20)
    at in.prolearn.newtours.testcases.VerifyNavigationTable.verifyTableLink(VerifyNavigationTable.java:26)
    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:100)
    at org.testng.internal.Invoker.invokeMethod(Invoker.java:646)
    at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:811)
    at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1137)
    at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:129)
    at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:112)
    at org.testng.TestRunner.privateRun(TestRunner.java:753)
    at org.testng.TestRunner.run(TestRunner.java:607)
    at org.testng.SuiteRunner.runTest(SuiteRunner.java:368)
    at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:363)
    at org.testng.SuiteRunner.privateRun(SuiteRunner.java:321)
    at org.testng.SuiteRunner.run(SuiteRunner.java:270)
    at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
    at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
    at org.testng.TestNG.runSuitesSequentially(TestNG.java:1284)
    at org.testng.TestNG.runSuitesLocally(TestNG.java:1209)
    at org.testng.TestNG.runSuites(TestNG.java:1124)
    at org.testng.TestNG.run(TestNG.java:1096)
    at org.testng.remote.AbstractRemoteTestNG.run(AbstractRemoteTestNG.java:132)
    at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:236)
    at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:81)


===============================================
    Default test
    Tests run: 1, Failures: 1, Skips: 0
===============================================

任何建议都会帮助我更好地理解这个工具。

由于

1 个答案:

答案 0 :(得分:0)

要查找表格的每一行,您可以使用此xpath:// tr [@ class ='mouseOut']

由于您只对链接(“a”节点)感兴趣,我建议您编写如下代码:

List<WebElement> linksInTable = driver.findElements(By.xpath("//tr[@class='mouseOut']//a"));
for(WebElement a : linksInTable){
    // write what you want to do with each link
}

您可能还会遇到问题,因为您在代码中使用“后退”。可能(您应该测试它以确保)每次返回主页时都应该再次找到Web元素。类似于:

for(int i=0;i<linksInTable.size();i++) {
   String text = linksInTable[i].getText();
   System.out.println(text);
   linksInTable[i].click();
   driver.navigate().back();
   linksInTable =  driver.findElements(By.xpath("//tr[@class='mouseOut']//a"));
}