Selenium automation error

How to get deal with various problems in your Selenium code.

How to get deal with various problems in your Selenium code.

Invalid Selector Exception

CSS and XPath Selectors are sometimes difficult to get correct.

Likely Cause

The CSS or XPath selector you are trying to use has invalid characters or an invalid query.

Possible Solutions

Run your selector through a validator service:

  • CSS Validator
  • xPath Validator

Or use a browser extension to get a known good value:

  • SelectorsHub

No Such Element Exception

The element can not be found at the exact moment you attempted to locate it.

Likely Cause

  • You are looking for the element in the wrong place (perhaps a previous action was unsuccessful).
  • You are looking for the element at the wrong time (the element has not shown up in the DOM, yet)
  • The locator has changed since you wrote the code

Possible Solutions

  • Make sure you are on the page you expect to be on, and that previous actions in your code completed correctly
  • Make sure you are using a proper Waiting Strategy
  • Update the locator with the browser’s devtools console or use a browser extension like:
    • SelectorsHub

Stale Element Reference Exception

An element goes stale when it was previously located, but can not be currently accessed.
Elements do not get relocated automatically; the driver creates a reference ID for the element and
has a particular place it expects to find it in the DOM. If it can not find the element
in the current DOM, any action using that element will result in this exception.

Common Causes

This can happen when:

  • You have refreshed the page, or the DOM of the page has dynamically changed.
  • You have navigated to a different page.
  • You have switched to another window or into or out of a frame or iframe.

Common Solutions

The DOM has changed

When the page is refreshed or items on the page have moved around, there is still
an element with the desired locator on the page, it is just no longer accessible
by the element object being used, and the element must be relocated before it can be used again.
This is often done in one of two ways:

  • Always relocate the element every time you go to use it. The likelihood of
    the element going stale in the microseconds between locating and using the element
    is small, though possible. The downside is that this is not the most efficient approach,
    especially when running on a remote grid.

  • Wrap the Web Element with another object that stores the locator, and caches the
    located Selenium element. When taking actions with this wrapped object, you can
    attempt to use the cached object if previously located, and if it is stale, exception
    can be caught, the element relocated with the stored locator, and the method re-tried.
    This is more efficient, but it can cause problems if the locator you’re using
    references a different element (and not the one you want) after the page has changed.

The Context has changed

Element objects are stored for a given context, so if you move to a different context —
like a different window or a different frame or iframe — the element reference will
still be valid, but will be temporarily inaccessible. In this scenario, it won’t
help to relocate the element, because it doesn’t exist in the current context.
To fix this, you need to make sure to switch back to the correct context before using the element.

The Page has changed

This scenario is when you haven’t just changed contexts, you have navigated to another page
and have destroyed the context in which the element was located.
You can’t just relocate it from the current context,
and you can’t switch back to an active context where it is valid. If this is the reason
for your error, you must both navigate back to the correct location and relocate it.

Support the Selenium Project

Want to support the Selenium project? Learn more or view the full list of sponsors.

Самые частые exceptions в Selenium и способы устранения

  • StaleElementReferenceException
  • NoSuchElementException
  • ElementClickInterceptedException
  • NoSuchWindowException
  • NoSuchFrameException
  • NoAlertPresentException
  • InvalidSelectorException
  • TimeoutException
  • ElementNotVisibleException
  • ElementNotSelectableException
  • NoSuchSessionException

Для начала, в чем разница между error и exception в Selenium?

  • Ошибки типа error — более серьезная вещь, возникают в тестовом окружении, и достаточно трудны для исправления (по крайней мере для новичка в QA)
  • Ошибки типа exception возникают в тестируемом приложении (AuT), и легко могут быть откорректированы тестировщиком, чему и посвящен данный материал.

3 самых частых exceptions в Selenium

Ошибка StaleElementReferenceException

Возможно, самый распространенный “эксепшен” у тестировщиков в Selenium (по крайней мере, о нем часто спрашивают на собеседованиях). Это сообщение означает, что веб-элемент по какой-то причине уже как бы “откреплен” от текущего DOM — сначала был в DOM, но после изменений в DOM он:

  • Был удален (реже)
  • “Завис” и теперь недоступен для действий с ним (чаще)

Причины ошибки StaleElementReferenceException

  • Веб-элемента нет в текущем состоянии DOM.
  • Веб-элемент удален из DOM. 

Почему так случилось? 

  • После перезагрузки страницы (Page Refresh)
  • Или выхода пользователя из страницы
  • Или веб-элемент по какой-то причине заменен на другой, с идентичными атрибутами

Как обработать ошибку StaleElementReferenceException

  • Обновить страницу, и теперь проверить веб-элемент. (Не рекомендуется, если при перезагрузке стираются сессионные данные / введенные пользователем данные)
  • Для проверки элемента воспользоваться интерфейсом JavaScriptExecutor
  • Имплементировать конструкцию try-catch, то есть “ловить” элемент блоком catch
  • Применить эксплицитное ожидание (explicit wait) — то есть ожидать появления элемента
  • Попытаться применить Dynamic XPath для обработки DOM-операций
  • Попытаться работать через Page Factory Model

Ошибка NoSuchElementException

WebDriver не может найти локальный элемент, то есть через метод FindBy кажется нельзя найти этот элемент.

Причины ошибки NoSuchElementException

  • Банальная причина: неправильно прописан локатор в методе findElement(by)
  • Имя элемента изменено разработчиком
  • Позиция элемента изменилась (если ищут локатором XPath)
  • Время загрузки элемента прописано слишком большое

Как устранить причину NoSuchElementException

  • “Пофиксить” некорректный локатор
  • Или добавить wait-команду
  • Или добавить блок try-catch, и/или эксплицитное ожидание элемента

Ошибка ElementClickInterceptedException

Невозможно выполнить команду, из-за того что элемент, “получающий” событие, скрывает за собой запрашиваемый элемент.

Причины ошибки ElementClickInterceptedException

  • Элементы “перекрываются” между собой
  • Один из элементов не загрузился как положено
  • Один из элементов отключен (disabled)
  • Элемент не в фокусе
  • Действие с некорректным веб-элементом
  • Этот элемент нельзя искать на странице по его координатам

Как устранить ElementClickInterceptedException

  • Добавить wait-ожидание пока элемент не будет доступен
  • Применить JavascriptExecutor для операции клика
  • Если элемент “некликабельный”, найти и закрыть “накрывающий” элемент (находящийся сверху нужного нам)
  • Если элементу нужен фокус, перейти на активный элемент и выполнить клик, используя класс Action.
  • Если для идентификации элемента используются координаты, попробовать сначала развернуть окно в полностью развернутое состояние.
Выше речь шла о самых распространенных “эксепшенах”, возникающих у тестировщиков в Selenium. Далее - о менее распространенных, поэтому о них чуть менее подробно.

NoSuchWindowException

Достаточно частая ошибка в Selenium WebDriver, когда текущий список окон некорректно обновился — предыдущего окна не существует, значит нельзя переключиться на него.

Решение: через метод WebDriver’а, driver.getWindowHandles().

NoSuchFrameException

Возникает аналогично предыдущему (NoSuchWindowException) — при переключении между фреймами один из них становится недоступен.

Решение: как в предыдущем примере.

NoAlertPresentException

Пользователь пытается перейти к еще несуществующему “алерту”. Такое бывает, когда тест “слишком быстрый”. Тест пытается найти “алерт”, который еще не открыт браузером.

Решение: чтобы избежать этой ошибки, или предотвратить ее, применяется эксплицитное или быстрое ожидание (explicit wait, fluent wait), желательно во всех случаях с alert’ами.

InvalidSelectorException

Некорректный селектор. В 99% случаев неправильно написано имя.

Решение: внимательность.

TimeoutException

Операция не выполнилась (не завершилась) в нужное время. 

Ожидания (waits) грамотно применяются опытными тестировщиками во избежание частой ошибки №2, NoSuchElementException, однако если элементы страницы не загрузились в прописанное wait-время, будет “выброшена” ошибка timeoutException.

Решение: тривиальное — узнать (оценить) среднее время загрузки страницы и “подобрать” к нему подходящее wait-время.

ElementNotVisibleException

WebDriver пытается найти элемент, по какой-то причине “заслоненный” другим, или в состоянии “невидимый”. 

Решение: узнать причину “невидимости” — это или проблема с вложенными элементами (и тогда найти и исправить проблемный элемент), или с “перекрытием элементов по времени” (и значит применить эксплицитное wait-ожидание).

ElementNotSelectableException

Этот exception относится к тому же типу, что InvalidElementStateException — элемент хотя и есть на странице, но выбран (отмечен, кликнут) быть не может.

Решение: грамотное применение wait-ожидания.

NoSuchSessionException

Такая ошибка “выбрасывается”, когда метод вызван уже после закрытия браузера — после того как браузер закрылся “самопроизвольно” в результате неожиданного сбоя.

Решение: браузер должен регулярно обновляться, и быть в стабильной версии.

“Exception” is a quite common term when it comes to programming, regardless of which language you use to write codes.

Exceptions in Selenium are like enemies for programmers—they are unavoidable. Even if you work with other automation testing tools such as Katalon Studio, you may still face these types of exceptions (because Katalon Studio is built on top of Selenium). They are, however, more easily fixable than bugs or errors as they can throw logical termination.

This article will provide you with a complete list of exceptions in Selenium as well as the cases in which they occur.

What are Selenium exceptions?

Definition

An exception is known as an unusual or unprecedented event that occurs during the execution of a software program or application. It is a runtime error of an unexpected result or event which influence and disrupt usual program flow. An exception is also considered as a fault.

Classification of Selenium exceptions

Selenium exceptions are divided into two types including Checked Exceptions and Unchecked Exceptions.

1. Checked Exceptions

Checked Exceptions are handled during the process of writing codes. These exceptions are handled before compiling the code, therefore, such exceptions are examined at the compile time.

2. Unchecked Exceptions

These exceptions are thrown at runtime. Unchecked exceptions are more catastrophic than the compile-time exception as it causes problems while running Automation pack in headless.

The complete list of exceptions in Selenium

1. ConnectionClosedException: This exception takes place when there is a disconnection in the driver.

2. ElementClickInterceptedException: The command could not be completed as the element receiving the events is concealing the element which was requested clicked.

3. ElementNotInteractableException: This Selenium exception is thrown when an element is presented in the DOM but it is impossible to interact with such element.

4. ElementNotSelectableException: This Selenium exception is thrown when an element is presented in the DOM but is unavailable for selection. Hence, it is impossible to interact with.

5. ElementNotVisibleException: This type of Selenium exception takes place when an existing element in DOM has a feature set as hidden. In this situation, elements are there, but you can not see and interact with the WebDriver.

6. ErrorHandler.UnknownServerException: Exception is used as a placeholder if the server returns an error without a stack trace.

7. ErrorInResponseException: This exception is thrown when a fault has occurred on the server-side. You can see it happens when interacting with the Firefox extension or the remote driver server.

8. ImeActivationFailedException: This exception occurs when IME engine activation has failed.

9. ImeNotAvailableException: This exception takes place when IME support is unavailable.

10. InsecureCertificateException: Navigation made the user agent to hit a certificate warning, which is caused by an invalid or expired TLS certificate.

11. InvalidArgumentException: This Selenium exception is thrown if an argument does not belong to the expected type.

12. InvalidCookieDomainException: This happens when you try to add a cookie under a different domain rather than the current URL.

13. InvalidCoordinatesException: This happens if the coordinates offered to an interacting operation are not valid.

14. InvalidElementStateException: This Selenium exception occurs if a command cannot be finished as the element is invalid.

15. InvalidSessionIdException: Takes place when the given session ID is not included in the list of active sessions, which means the session does not exist or is inactive either.

16. InvalidSwitchToTargetException: Happens if the frame or window target to be switched does not exist.

17. JavascriptException: This problem happens when executing JavaScript supplied by the user.

18. JsonException: Happens when you afford to get the session capabilities where the session is not created.

19. MoveTargetOutOfBoundsException: Takes place if the target provided to the ActionChains move() methodology is not valid. For example: out of the document.

20. NoAlertPresentException: Happens when you switch to no presented alert.

21. NoSuchAttributeException: Occurs when the attribute of the element could not be found.

22. NoSuchContextException: Happens in mobile device testing and is thrown by ContextAware.

23. NoSuchCookieException: This exception is thrown if there is no cookie matching with the given path name found amongst the associated cookies of the current browsing context’s active document.

24. NoSuchElementException: Happens if an element could not be found.

25. NoSuchFrameException: Takes place if frame target to be switch does not exist.

26. NoSuchWindowException: Occurs if window target to be switched does not exist.

27. NotFoundException: This exception is a subclass of WebDriverException. It happens when an element on the DOM does not exist.

28. RemoteDriverServerException: This Selenium exception is thrown when the server does not respond due to the problem that the capabilities described are not proper.

29. ScreenshotException: It is impossible to capture a screen.

30. ScriptTimeoutException: Thrown when executeAsyncScript takes more time than the given time limit to return the value.

31. SessionNotCreatedException: A new session could not be successfully created.

32. SessionNotFoundException: The WebDriver is performing the action right after you quit the browser.

33. StaleElementReferenceException: This Selenium exception happens if the web element is detached from the current DOM.

34. TimeoutException: Thrown when there is not enough time for a command to be completed.

35. UnableToCreateProfileException: You can open a browser with certain options using profiles, but sometimes a new version of the Selenium driver server or browser may not support the profiles.

36. UnableToSetCookieException: Occurs if a driver is unable to set a cookie.

37. UnexpectedAlertPresentException: This Selenium exception happens when there is the appearance of an unexpected alert.

38. UnexpectedTagNameException: Happens if a support class did not get a web element as expected.

39. UnhandledAlertException: It happens when there is an alert, but WebDriver is unable to perform Alert operation.

40. UnknownMethodException: Thrown when the requested command matches with a known URL but not matching with a methodology for that URL.

41. UnreachableBrowserException: This Selenium exception happens if the browser is unable to be opened or has crashed because of some reasons.

42. UnsupportedCommandException: Occurs when remote WebDriver does not send valid commands as expected.

43. WebDriverException: This takes place when the WebDriver is performing the action right after you close the browser.

Selenium exceptions handling

What is Exception handling?

In a software program, an atypical event (e.g. unrecognized messages) can interfere with the regular execution flow. These events, if not handled properly, can result in termination of the program by immediate throwing exceptions. Handling exceptions is the process of managing these atypical events in order to prevent such problems from arising.

Selenium exception solutions

In order to handle these above types of Selenium exceptions, this article will discuss some compiler directives to support exception handling.

  • Throw: Throw keyword is used to throw exception to the runtime to handle it.

// Method Signature public static void anyFunction() throws Exception{ try{ // write your code here }catch (Exception e){ // Do whatever you wish to do here // Now throw the exception back to the system throw(e); } }

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

// Method Signature

public static void anyFunction ( ) throws Exception {

try {

// write your code here

} catch ( Exception e ) {

// Do whatever you wish to do here

// Now throw the exception back to the system

throw ( e ) ;

}

}

  • Multiple Catch blocks: You can have multiple @catch() blocks to catch different types of exception. The syntax for multiple catch blocks looks like the following:

try { //Some code }catch(ExceptionType1 e1){ //Code for Handling the Exception 1 }catch(ExceptionType2 e2){ //Code for Handling the Exception 2 }

try

{

   //Some code

} catch ( ExceptionType1 e1 ) {

   //Code for Handling the Exception 1

} catch ( ExceptionType2 e2 ) {

   //Code for Handling the Exception 2

}

  • Try/Catch: A @try block encloses code that can potentially throw an exception. A @catch() block contains exception-handling logic for exceptions thrown in a @try block. Code within a try/catch block is referred to as protected code, and the syntax for using try/catch looks like the following:

try { // Some code }catch(Exception e){ // Code for Handling the exception }

try

{

// Some code

} catch ( Exception e ) {

// Code for Handling the exception

}

  • Finally: A @finally block contains code that must be executed whether an exception is thrown or not:

try { //Protected code }catch(ExceptionType1 e1) { //Catch block }catch(ExceptionType2 e2) { //Catch block }catch(ExceptionType3 e3) { //Catch block }finally { //The finally block always executes. }

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

try

{

   //Protected code

} catch ( ExceptionType1 e1 )

{

   //Catch block

} catch ( ExceptionType2 e2 )

{

   //Catch block

} catch ( ExceptionType3 e3 )

{

   //Catch block

} finally

{

   //The finally block always executes.

}

Selenium exception examples

Example 1: TimeoutException using Selenium WebDriver.

import static com.kms.katalon.core.testobject.ObjectRepository.findTestObject import org.openqa.selenium.TimeoutException import com.kms.katalon.core.logging.KeywordLogger import com.kms.katalon.core.util.KeywordUtil import com.kms.katalon.core.webui.keyword.WebUiBuiltInKeywords as WebUI try{ WebUI.click(findTestObject(«Page_Register/btn_register»)) }catch (TimeoutException toe) { WebUI.waitForElementClickable(findTestObject(«Page_Register/btn_register»), 20) WebUI.click(findTestObject(«Page_Register/btn_register»)) }catch (Exception e) { KeywordUtil.markError(«Register button is not found.») throw(e); }

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

import static com . kms . katalon . core . testobject . ObjectRepository . findTestObject

import org . openqa . selenium . TimeoutException

import com . kms . katalon . core . logging . KeywordLogger

import com . kms . katalon . core . util . KeywordUtil

import com . kms . katalon . core . webui . keyword . WebUiBuiltInKeywords as WebUI

try {

WebUI . click ( findTestObject ( «Page_Register/btn_register» ) )

} catch ( TimeoutException toe ) {

WebUI . waitForElementClickable ( findTestObject ( «Page_Register/btn_register» ) , 20 )

WebUI . click ( findTestObject ( «Page_Register/btn_register» ) )

} catch ( Exception e ) {

KeywordUtil . markError ( «Register button is not found.» )

throw ( e ) ;

}

Example 2: Let’s assume that in Selenium WebDriver you want to verify the presence of any element on the page. You would not be able to get this with an element locator. If the element is present, your locator will work and you will easily be able to print that the element is present. However, in this case, your element is not present on the page, your locator fails and simply throws the exception. Therefore, this case would be easily solved by using the self-written function.

import static com.kms.katalon.core.testobject.ObjectRepository.findTestObject import org.openqa.selenium.WebDriver import com.kms.katalon.core.webui.common.WebUiCommonHelper boolean verifyObjectPresent() { try { WebUiCommonHelper.findWebElement(findTestObject(«Page_Report/lblReport»), 20) return true; } catch (Exception e) { return false; } }

import static com . kms . katalon . core . testobject . ObjectRepository . findTestObject

import org . openqa . selenium . WebDriver

import com . kms . katalon . core . webui . common . WebUiCommonHelper

boolean verifyObjectPresent ( ) { 

try {

WebUiCommonHelper . findWebElement ( findTestObject ( «Page_Report/lblReport» ) , 20 ) 

return true ;

} catch ( Exception e ) {

return false ;

} 

}

Conclusion

We have listed all types of exceptions in Selenium along with their explanations above. From here, you can create robust and optimal codes in Selenium as well as Katalon Studio by handling these exceptions wisely. We hope this article will be a quick reference for you to tackle exceptions in Selenium and Katalon Studio.

Download Katalon now

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Selected boot image did not authenticate как исправить
  • Select variable to plot матлаб как исправить ошибку
  • Select error column lists do not match
  • Select corona as your production render first как исправить
  • Select action an error occurred while trying to copy a file

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии