Selenium WebDriver - 获取" java.lang.NullPointerException"尝试使用" getAttribute"

时间:2016-12-15 12:37:12

标签: java selenium selenium-webdriver webdriver ui-automation

我正在尝试使用selenium的getAttribute函数获取属性值,但获取NullPointerException。可能的原因似乎是属性值开头的双引号。

有人可以提出其他选择吗?

Selenium Java命令:

driver.findElement(By.xpath("//tbody[@role='alert']/tr[@class='error']")).getAttribute("data-suppression-reason");

HTML code snippet:

<tbody role="alert" aria-live="polite" aria-relevant="all">
    <tr class="odd">
    <tr class="even">
    <tr class="error" data-suppression-reason=""Email" is empty.">
    <tr class="error" data-suppression-reason=""Email" is empty.">
    <tr class="odd">
</tbody>

堆栈追踪:

java.lang.NullPointerException
    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:84)
    at org.testng.internal.Invoker.invokeMethod(Invoker.java:714)
    at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:901)
    at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1231)
    at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:127)
    at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:111)
    at org.testng.TestRunner.privateRun(TestRunner.java:767)
    at org.testng.TestRunner.run(TestRunner.java:617)
    at org.testng.SuiteRunner.runTest(SuiteRunner.java:334)
    at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:329)
    at org.testng.SuiteRunner.privateRun(SuiteRunner.java:291)
    at org.testng.SuiteRunner.run(SuiteRunner.java:240)
    at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
    at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
    at org.testng.TestNG.runSuitesSequentially(TestNG.java:1224)
    at org.testng.TestNG.runSuitesLocally(TestNG.java:1149)
    at org.testng.TestNG.run(TestNG.java:1057)
    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)

2 个答案:

答案 0 :(得分:1)

用你的html测试了你的xpath,2个问题。

  1. 关闭tr个元素。它可能适用于html但xpath期望格式良好的xml

  2. 属性值的双引号也将被视为格式错误的xml。请逃避他们,例如使用&quot;代替""

答案 1 :(得分:1)

试试这个

List <WebElement> trElement = driver.findElements(By.xpath("//tbody[@role='alert']/tr[@class='error']"));
for(WebElement tr_ele : trElement){
    sysout(tr_ele.getAttribute("data-suppression-reason"));
}

这应该使用class = Error打印每个元素的属性内容。考虑你的xpath是否合适。如果不工作,那么你需要调查你的Element xpath。

或者您可以在上面的代码中尝试以下定位器。

By.xpath("//td[@class='error']")
By.Classname("error")
css = "td[class='error']"

希望这会有所帮助