简体   繁体   English

如何处理硒NoSuchElementException

[英]How to handle selenium NoSuchElementException

I am having a little trouble understanding how I should handle selenium when it can't find an element. 我在理解硒找不到元素时应如何处理时遇到了一些麻烦。 My current code is this: 我当前的代码是这样的:

WebDriver driver = new PhantomJSDriver();

for (FeedItem item : items){

    String url = item.getLink();
    System.out.println("Retrieving: " + item.getTitle() + " from: " + url);
    driver.get(url);
    System.out.println("Got URL");

    try{
        WebElement title = driver.findElement(By.className("story-body__h1"));  // NoSuchElementException is thrown here
        WebElement body = driver.findElement(By.className("story-body__inner"));
        List<WebElement> story = body.findElements(By.tagName("p"));

        for (WebElement part : story){
            System.out.println(part.getText());
        }

        System.out.println();
        } catch (NoSuchElementException | ScreenshotException e) {
            System.err.println("Unable to find element");
        } 
    }
    driver.close();
}

but when ever it can't find the element I get this error: 但是无论何时找不到元素我都会收到此错误:

Exception in thread "main" org.openqa.selenium.NoSuchElementException: {"errorMessage":"Unable to find element with class name 'story-body__h1'","request":{"headers":{"Accept-Encoding":"gzip,deflate","Connection":"Keep-Alive","Content-Length":"47","Content-Type":"application/json; charset=utf-8","Host":"localhost:2468","User-Agent":"Apache-HttpClient/4.5.1 (Java/1.7.0_03)"},"httpVersion":"1.1","method":"POST","post":"{\"using\":\"class name\",\"value\":\"story-body__h1\"}","url":"/element","urlParsed":{"anchor":"","query":"","file":"element","directory":"/","path":"/element","relative":"/element","port":"","host":"","password":"","user":"","userInfo":"","authority":"","protocol":"","source":"/element","queryKey":{},"chunks":["element"]},"urlOriginal":"/session/980187a0-890f-11e5-9de4-cb2118f0c6b9/element"}}
Command duration or timeout: 855 milliseconds
For documentation on this error, please visit: http://seleniumhq.org/exceptions/no_such_element.html
Build info: version: '2.48.2', revision: '41bccdd', time: '2015-10-09 19:55:52'
System info: host: 'PICKUPA', ip: '10.111.77.54', os.name: 'Windows 7', os.arch: 'amd64', os.version: '6.1', java.version: '1.7.0_03'
*** Element info: {Using=class name, value=story-body__h1}
Session ID: 980187a0-890f-11e5-9de4-cb2118f0c6b9
Driver info: org.openqa.selenium.phantomjs.PhantomJSDriver
Capabilities [{platform=XP, acceptSslCerts=false, javascriptEnabled=true, browserName=phantomjs, rotatable=false, driverVersion=1.2.0, locationContextEnabled=false, version=2.0.0, databaseEnabled=false, cssSelectorsEnabled=true, handlesAlerts=false, browserConnectionEnabled=false, nativeEvents=true, proxy={proxyType=direct}, webStorageEnabled=false, driverName=ghostdriver, applicationCacheEnabled=false, takesScreenshot=true}]
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:525)
    at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:206)
    at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:158)
    at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:647)
    at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:353)
    at org.openqa.selenium.remote.RemoteWebDriver.findElementByClassName(RemoteWebDriver.java:467)
    at org.openqa.selenium.By$ByClassName.findElement(By.java:391)
    at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:345)
    at com.agi.cat.crawler.NewsCrawler.main(NewsCrawler.java:72)
Caused by: org.openqa.selenium.remote.ScreenshotException: Screen shot has been taken
Build info: version: '2.48.2', revision: '41bccdd', time: '2015-10-09 19:55:52'
System info: host: 'PICKUPA', ip: '10.111.77.54', os.name: 'Windows 7', os.arch: 'amd64', os.version: '6.1', java.version: '1.7.0_03'
Driver info: driver.version: RemoteWebDriver
    at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:138)
    ... 6 more
Caused by: org.openqa.selenium.NoSuchElementException: {"errorMessage":"Unable to find element with class name 'story-body__h1'","request":{"headers":{"Accept-Encoding":"gzip,deflate","Connection":"Keep-Alive","Content-Length":"47","Content-Type":"application/json; charset=utf-8","Host":"localhost:2468","User-Agent":"Apache-HttpClient/4.5.1 (Java/1.7.0_03)"},"httpVersion":"1.1","method":"POST","post":"{\"using\":\"class name\",\"value\":\"story-body__h1\"}","url":"/element","urlParsed":{"anchor":"","query":"","file":"element","directory":"/","path":"/element","relative":"/element","port":"","host":"","password":"","user":"","userInfo":"","authority":"","protocol":"","source":"/element","queryKey":{},"chunks":["element"]},"urlOriginal":"/session/980187a0-890f-11e5-9de4-cb2118f0c6b9/element"}}
For documentation on this error, please visit: http://seleniumhq.org/exceptions/no_such_element.html
Build info: version: '2.48.2', revision: '41bccdd', time: '2015-10-09 19:55:52'
System info: host: 'PICKUPA', ip: '10.111.77.54', os.name: 'Windows 7', os.arch: 'amd64', os.version: '6.1', java.version: '1.7.0_03'
Driver info: driver.version: unknown

and the thread becomes blocked. 并且线程被阻塞。 (I can't click stop in eclipse, I have to use terminate and remove from the debugger view to stop its execution) (我无法在eclipse中单击“停止”,我必须使用“终止”并从调试器视图中删除以停止其执行)

How should I be handling this error? 我应该如何处理此错误?

EDIT: If I just catch all Exceptions then it continues as expected, so what exception should I be catching? 编辑:如果我只是捕获所有异常,然后按预期方式继续进行,那么我应该捕获什么异常?

Check if you've imported the correct class. 检查您是否导入了正确的类。 It should be 它应该是

import org.openqa.selenium.NoSuchElementException

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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