1

У меня возникли проблемы с пониманием того, как я должен обращаться с селеном, когда он не может найти элемент. Мой текущий код заключается в следующем:Как обращаться с селеном NoSuchElementException

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

но когда-либо он не может найти элемент я получаю эту ошибку:

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 

и поток блокируется. (Я не могу щелкнуть стоп в eclipse, я должен использовать завершение и удалить из представления отладчика, чтобы остановить его выполнение)

Как я должен обрабатывать эту ошибку?

EDIT: Если я просто поймаю все Исключения, то он будет продолжаться, как ожидалось, и какое исключение я должен ловить?

+1

Проверьте, не импортирован ли правильный класс. Это должно быть 'import org.openqa.selenium.NoSuchElementException' и NOT' import java.util.NoSuchElementException'. – JRodDynamite

+0

@JasonEstibeiro Это была проблема, спасибо – rj93

ответ

1

Проверьте, не импортирован ли правильный класс. Это должно быть

import org.openqa.selenium.NoSuchElementException 
Смежные вопросы