I am writing automation test in Selenium using Python. One element may or may not be present. I am trying to handle it with below code, it works when element is present. But script fails when element is not present, I want to continue to next statement if element is not present.
try:
elem = driver.find_element_by_xpath(".//*[@id='SORM_TB_ACTION0']")
elem.click()
except nosuchelementexception:
pass
Error —
selenium.common.exceptions.NoSuchElementException: Message: Unable to locate element:{"method":"xpath","selector":".//*[@id='SORM_TB_ACTION0']"}
asked Jun 24, 2016 at 21:56
Are you not importing the exception?
from selenium.common.exceptions import NoSuchElementException
try:
elem = driver.find_element_by_xpath(".//*[@id='SORM_TB_ACTION0']")
elem.click()
except NoSuchElementException: #spelling error making this code not work as expected
pass
answered Jun 24, 2016 at 22:04
Levi NoeckerLevi Noecker
3,1121 gold badge15 silver badges29 bronze badges
You can see if the element exists and then click it if it does. No need for exceptions. Note the plural «s» in .find_elements_*
.
elem = driver.find_elements_by_xpath(".//*[@id='SORM_TB_ACTION0']")
if len(elem) > 0
elem[0].click()
answered Jun 24, 2016 at 23:11
JeffCJeffC
22.1k5 gold badges31 silver badges55 bronze badges
2
the way you are doing it is fine.. you are just trying to catch the wrong exception. It is named NoSuchElementException
not nosuchelementexception
answered May 22, 2017 at 19:38
Corey GoldbergCorey Goldberg
58.6k28 gold badges128 silver badges142 bronze badges
Handling Selenium NoSuchExpressionException
from selenium.common.exceptions import NoSuchElementException
try:
elem = driver.find_element_by_xpath
candidate_Name = j.find_element_by_xpath('.//span[@aria-hidden="true"]').text
except NoSuchElementException:
try:
candidate_Name = j.find_element_by_xpath('.//a[@class="app-aware link"]').text
except NoSuchElementException:
candidate_Name = "NAN"
pass
answered Jan 13, 2022 at 20:34
dataninsightdataninsight
1,0115 silver badges13 bronze badges
Why not simplify and use logic like this? No exceptions needed.
if elem.is_displayed():
elem.click()
answered Jun 24, 2016 at 22:26
1
NoSuchElementException in Selenium
org.openqa.selenium.NoSuchElementException
Selenium WebDriver is a widely used tool for automating browsers through various programming languages, including Java. One common exception that engineers encounter when working with Selenium is NoSuchElementException. This article provides a comprehensive understanding of NoSuchElementException, its causes, and how to handle it effectively. Additionally, it includes a Java code example to demonstrate handling the exception.
What is NoSuchElementException?
NoSuchElementException is thrown by findElement()
method in Selenium WebDriver when the desired element cannot be located using the specified locator (such as an ID, name, class, CSS selector, or XPath). This exception indicates that the web element you are trying to interact with is not present on the web page at the time the method is executed.
Primary Causes of NoSuchElementException
The most frequent reasons for encountering this exception include:
- Changes in HTML/XML structure: The target element now has a different locator than it did previously. This situation is especially common in actively developed projects, where UI elements and their locators might change frequently.
- Element no longer present on the page/screen: The element was previously on the current page but can no longer be located. This issue may stem from the current step or a prior step, leading to a mismatch between the expected and actual page states.
- Timing issues: The element might not yet be loaded on the page, especially in dynamic web applications with AJAX and JavaScript. In this case, Selenium might be attempting to find the element before it has been rendered, resulting in NoSuchElementException.
How to deal with the NoSuchElementException exception
To troubleshoot NoSuchElementException effectively, follow these steps:
- Verify the locator: As a first step, you ought to find out what kind of issue you are dealing with. Is the element still there and can’t be found, or is it no longer present on the page? To do this, you can setup Selenium to not to close the browser after the test failure, and run the test. Once you get the exception, you can inspect the page that is open in the browser. Double-check that the locator being used is correct and up-to-date. Inspect the HTML source code to confirm that the locator uniquely identifies the target element on the page.
- Wait for the element: Implement implicit (not recommended unless necessary) or explicit (recommended) waits to give the element time to load before attempting to interact with it. This approach helps to ensure that Selenium does not attempt to find the element before it has been rendered on the page.
Code example:
import org.openqa.selenium.By; import org.openqa.selenium.NoSuchElementException; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; public class NoSuchElementExceptionExample { public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "path/to/chromedriver"); WebDriver driver = new ChromeDriver(); WebDriverWait wait = new WebDriverWait(driver, 10); // 10-second explicit wait try { driver.get("https://example.com"); // Wait until the element is present and visible WebElement element = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("elementId"))); // Perform actions on the element element.click(); } catch (NoSuchElementException e) { System.out.println("Element not found: " + e.getMessage()); } finally { driver.quit(); } } }
Here, the example demonstrates handling NoSuchElementException in a Selenium WebDriver test. It imports necessary classes, initializes WebDriver and WebDriverWait, and uses a try-catch block to navigate to a webpage, wait for an element to be visible, and perform actions on the element. If NoSuchElementException is thrown, the error message is printed, and the browser and WebDriver session are terminated in the finally block.
By using this code example as a guide, you can implement error handling for NoSuchElementException in your Selenium tests, while ensuring that your automation script waits for the elements to be visible before interacting with them.
The main reason for NoSuchElementException
The main problem that leads to this exception is that in Selenium, you hook up to details of implementation. Because Selenium hooks up to a locator, which is a detail of implementation, not end-user’s level description. You can learn why Selenium is not an adequate solution for modern websites here.
To give you a different perspective, testRigor users will never face exception errors like the one discussed in this article — since testRigor’s engine scans the page for you, identifies all possible locators for each element, and machine learning algorithms fine-tune wait times as needed. You will never have to worry about element locators with testRigor.
Join the next wave of functional testing now.
A testRigor specialist will walk you through our platform with a custom demo.
Самые частые 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
Такая ошибка “выбрасывается”, когда метод вызван уже после закрытия браузера — после того как браузер закрылся “самопроизвольно” в результате неожиданного сбоя.
Решение: браузер должен регулярно обновляться, и быть в стабильной версии.
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.keys import Keys
from selenium.common.exceptions import NoSuchElementException
import time
PATH=r»C:UsersGUTKRISHchromedriver.exe»
driver = webdriver.Chrome(PATH)
driver.get(«http://demo.guru99.com/test/newtours/»)
try:
user_name = driver.find_element_by_name(«userNam»)
user_name.send_keys(«mercury»)
except NoSuchElementException:
print(«exception handled»)
password = driver.find_element_by_name(«password»)
submit = driver.find_element_by_name(«submit»)
password.send_keys(«mercury»)
submit.click()
Exceptions that may happen in all the webdriver code.
Exceptions
ElementClickInterceptedException (msg, …) |
The Element Click command could not be completed because the element receiving the events is obscuring the element that was requested to be clicked. |
ElementNotInteractableException (msg, screen, …) |
Thrown when an element is present in the DOM but interactions with that element will hit another element due to paint order. |
ElementNotSelectableException (msg, screen, …) |
Thrown when trying to select an unselectable element. |
ElementNotVisibleException (msg, screen, …) |
Thrown when an element is present on the DOM, but it is not visible, and so is not able to be interacted with. |
ImeActivationFailedException (msg, screen, …) |
Thrown when activating an IME engine has failed. |
ImeNotAvailableException (msg, screen, stacktrace) |
Thrown when IME support is not available. |
InsecureCertificateException (msg, screen, …) |
Navigation caused the user agent to hit a certificate warning, which is usually the result of an expired or invalid TLS certificate. |
InvalidArgumentException (msg, screen, stacktrace) |
The arguments passed to a command are either invalid or malformed. |
InvalidCookieDomainException (msg, screen, …) |
Thrown when attempting to add a cookie under a different domain than the current URL. |
InvalidCoordinatesException (msg, screen, …) |
The coordinates provided to an interaction’s operation are invalid. |
InvalidElementStateException (msg, screen, …) |
Thrown when a command could not be completed because the element is in an invalid state. |
InvalidSelectorException (msg, screen, stacktrace) |
Thrown when the selector which is used to find an element does not return a WebElement. |
InvalidSessionIdException (msg, screen, …) |
Occurs if the given session id is not in the list of active sessions, meaning the session either does not exist or that it’s not active. |
InvalidSwitchToTargetException (msg, screen, …) |
Thrown when frame or window target to be switched doesn’t exist. |
JavascriptException (msg, screen, stacktrace) |
An error occurred while executing JavaScript supplied by the user. |
MoveTargetOutOfBoundsException (msg, screen, …) |
Thrown when the target provided to the ActionsChains move() method is invalid, i.e. |
NoAlertPresentException (msg, screen, stacktrace) |
Thrown when switching to no presented alert. |
NoSuchAttributeException (msg, screen, stacktrace) |
Thrown when the attribute of element could not be found. |
NoSuchCookieException (msg, screen, stacktrace) |
No cookie matching the given path name was found amongst the associated cookies of the current browsing context’s active document. |
NoSuchElementException (msg, screen, stacktrace) |
Thrown when element could not be found. |
NoSuchFrameException (msg, screen, stacktrace) |
Thrown when frame target to be switched doesn’t exist. |
NoSuchShadowRootException (msg, screen, …) |
Thrown when trying to access the shadow root of an element when it does not have a shadow root attached. |
NoSuchWindowException (msg, screen, stacktrace) |
Thrown when window target to be switched doesn’t exist. |
ScreenshotException (msg, screen, stacktrace) |
A screen capture was made impossible. |
SessionNotCreatedException (msg, screen, …) |
A new session could not be created. |
StaleElementReferenceException (msg, screen, …) |
Thrown when a reference to an element is now “stale”. |
TimeoutException (msg, screen, stacktrace) |
Thrown when a command does not complete in enough time. |
UnableToSetCookieException (msg, screen, …) |
Thrown when a driver fails to set a cookie. |
UnexpectedAlertPresentException (msg, screen, …) |
Thrown when an unexpected alert has appeared. |
UnexpectedTagNameException (msg, screen, …) |
Thrown when a support class did not get an expected web element. |
UnknownMethodException (msg, screen, stacktrace) |
The requested command matched a known URL but did not match any methods for that URL. |
WebDriverException (msg, screen, stacktrace) |
Base webdriver exception. |
-
exception
selenium.common.exceptions.
ElementClickInterceptedException
(msg: Optional[str] = None, screen: Optional[str] = None, stacktrace: Optional[Sequence[str]] = None)[source]¶ -
The Element Click command could not be completed because the element
receiving the events is obscuring the element that was requested to be
clicked.-
args
¶
-
with_traceback
()¶ -
Exception.with_traceback(tb) –
set self.__traceback__ to tb and return self.
-
-
exception
selenium.common.exceptions.
ElementNotInteractableException
(msg: Optional[str] = None, screen: Optional[str] = None, stacktrace: Optional[Sequence[str]] = None)[source]¶ -
Thrown when an element is present in the DOM but interactions with that
element will hit another element due to paint order.-
args
¶
-
with_traceback
()¶ -
Exception.with_traceback(tb) –
set self.__traceback__ to tb and return self.
-
-
exception
selenium.common.exceptions.
ElementNotSelectableException
(msg: Optional[str] = None, screen: Optional[str] = None, stacktrace: Optional[Sequence[str]] = None)[source]¶ -
Thrown when trying to select an unselectable element.
For example, selecting a ‘script’ element.
-
args
¶
-
with_traceback
()¶ -
Exception.with_traceback(tb) –
set self.__traceback__ to tb and return self.
-
-
exception
selenium.common.exceptions.
ElementNotVisibleException
(msg: Optional[str] = None, screen: Optional[str] = None, stacktrace: Optional[Sequence[str]] = None)[source]¶ -
Thrown when an element is present on the DOM, but it is not visible, and
so is not able to be interacted with.Most commonly encountered when trying to click or read text of an
element that is hidden from view.-
args
¶
-
with_traceback
()¶ -
Exception.with_traceback(tb) –
set self.__traceback__ to tb and return self.
-
-
exception
selenium.common.exceptions.
ImeActivationFailedException
(msg: Optional[str] = None, screen: Optional[str] = None, stacktrace: Optional[Sequence[str]] = None)[source]¶ -
Thrown when activating an IME engine has failed.
-
args
¶
-
with_traceback
()¶ -
Exception.with_traceback(tb) –
set self.__traceback__ to tb and return self.
-
-
exception
selenium.common.exceptions.
ImeNotAvailableException
(msg: Optional[str] = None, screen: Optional[str] = None, stacktrace: Optional[Sequence[str]] = None)[source]¶ -
Thrown when IME support is not available.
This exception is thrown for every IME-related method call if IME
support is not available on the machine.-
args
¶
-
with_traceback
()¶ -
Exception.with_traceback(tb) –
set self.__traceback__ to tb and return self.
-
-
exception
selenium.common.exceptions.
InsecureCertificateException
(msg: Optional[str] = None, screen: Optional[str] = None, stacktrace: Optional[Sequence[str]] = None)[source]¶ -
Navigation caused the user agent to hit a certificate warning, which is
usually the result of an expired or invalid TLS certificate.-
args
¶
-
with_traceback
()¶ -
Exception.with_traceback(tb) –
set self.__traceback__ to tb and return self.
-
-
exception
selenium.common.exceptions.
InvalidArgumentException
(msg: Optional[str] = None, screen: Optional[str] = None, stacktrace: Optional[Sequence[str]] = None)[source]¶ -
The arguments passed to a command are either invalid or malformed.
-
args
¶
-
with_traceback
()¶ -
Exception.with_traceback(tb) –
set self.__traceback__ to tb and return self.
-
-
exception
selenium.common.exceptions.
InvalidCookieDomainException
(msg: Optional[str] = None, screen: Optional[str] = None, stacktrace: Optional[Sequence[str]] = None)[source]¶ -
Thrown when attempting to add a cookie under a different domain than the
current URL.-
args
¶
-
with_traceback
()¶ -
Exception.with_traceback(tb) –
set self.__traceback__ to tb and return self.
-
-
exception
selenium.common.exceptions.
InvalidCoordinatesException
(msg: Optional[str] = None, screen: Optional[str] = None, stacktrace: Optional[Sequence[str]] = None)[source]¶ -
The coordinates provided to an interaction’s operation are invalid.
-
args
¶
-
with_traceback
()¶ -
Exception.with_traceback(tb) –
set self.__traceback__ to tb and return self.
-
-
exception
selenium.common.exceptions.
InvalidElementStateException
(msg: Optional[str] = None, screen: Optional[str] = None, stacktrace: Optional[Sequence[str]] = None)[source]¶ -
Thrown when a command could not be completed because the element is in
an invalid state.This can be caused by attempting to clear an element that isn’t both
editable and resettable.-
args
¶
-
with_traceback
()¶ -
Exception.with_traceback(tb) –
set self.__traceback__ to tb and return self.
-
-
exception
selenium.common.exceptions.
InvalidSelectorException
(msg: Optional[str] = None, screen: Optional[str] = None, stacktrace: Optional[Sequence[str]] = None)[source]¶ -
Thrown when the selector which is used to find an element does not
return a WebElement.Currently this only happens when the selector is an xpath expression
and it is either syntactically invalid (i.e. it is not a xpath
expression) or the expression does not select WebElements (e.g.
“count(//input)”).-
args
¶
-
with_traceback
()¶ -
Exception.with_traceback(tb) –
set self.__traceback__ to tb and return self.
-
-
exception
selenium.common.exceptions.
InvalidSessionIdException
(msg: Optional[str] = None, screen: Optional[str] = None, stacktrace: Optional[Sequence[str]] = None)[source]¶ -
Occurs if the given session id is not in the list of active sessions,
meaning the session either does not exist or that it’s not active.-
args
¶
-
with_traceback
()¶ -
Exception.with_traceback(tb) –
set self.__traceback__ to tb and return self.
-
-
exception
selenium.common.exceptions.
InvalidSwitchToTargetException
(msg: Optional[str] = None, screen: Optional[str] = None, stacktrace: Optional[Sequence[str]] = None)[source]¶ -
Thrown when frame or window target to be switched doesn’t exist.
-
args
¶
-
with_traceback
()¶ -
Exception.with_traceback(tb) –
set self.__traceback__ to tb and return self.
-
-
exception
selenium.common.exceptions.
JavascriptException
(msg: Optional[str] = None, screen: Optional[str] = None, stacktrace: Optional[Sequence[str]] = None)[source]¶ -
An error occurred while executing JavaScript supplied by the user.
-
args
¶
-
with_traceback
()¶ -
Exception.with_traceback(tb) –
set self.__traceback__ to tb and return self.
-
-
exception
selenium.common.exceptions.
MoveTargetOutOfBoundsException
(msg: Optional[str] = None, screen: Optional[str] = None, stacktrace: Optional[Sequence[str]] = None)[source]¶ -
Thrown when the target provided to the ActionsChains move() method is
invalid, i.e. out of document.-
args
¶
-
with_traceback
()¶ -
Exception.with_traceback(tb) –
set self.__traceback__ to tb and return self.
-
-
exception
selenium.common.exceptions.
NoAlertPresentException
(msg: Optional[str] = None, screen: Optional[str] = None, stacktrace: Optional[Sequence[str]] = None)[source]¶ -
Thrown when switching to no presented alert.
This can be caused by calling an operation on the Alert() class when
an alert is not yet on the screen.-
args
¶
-
with_traceback
()¶ -
Exception.with_traceback(tb) –
set self.__traceback__ to tb and return self.
-
-
exception
selenium.common.exceptions.
NoSuchAttributeException
(msg: Optional[str] = None, screen: Optional[str] = None, stacktrace: Optional[Sequence[str]] = None)[source]¶ -
Thrown when the attribute of element could not be found.
You may want to check if the attribute exists in the particular
browser you are testing against. Some browsers may have different
property names for the same property. (IE8’s .innerText vs. Firefox
.textContent)-
args
¶
-
with_traceback
()¶ -
Exception.with_traceback(tb) –
set self.__traceback__ to tb and return self.
-
-
exception
selenium.common.exceptions.
NoSuchCookieException
(msg: Optional[str] = None, screen: Optional[str] = None, stacktrace: Optional[Sequence[str]] = None)[source]¶ -
No cookie matching the given path name was found amongst the associated
cookies of the current browsing context’s active document.-
args
¶
-
with_traceback
()¶ -
Exception.with_traceback(tb) –
set self.__traceback__ to tb and return self.
-
-
exception
selenium.common.exceptions.
NoSuchElementException
(msg: Optional[str] = None, screen: Optional[str] = None, stacktrace: Optional[Sequence[str]] = None)[source]¶ -
Thrown when element could not be found.
- If you encounter this exception, you may want to check the following:
-
- Check your selector used in your find_by…
- Element may not yet be on the screen at the time of the find operation,
(webpage is still loading) see selenium.webdriver.support.wait.WebDriverWait()
for how to write a wait wrapper to wait for an element to appear.
-
args
¶
-
with_traceback
()¶ -
Exception.with_traceback(tb) –
set self.__traceback__ to tb and return self.
-
exception
selenium.common.exceptions.
NoSuchFrameException
(msg: Optional[str] = None, screen: Optional[str] = None, stacktrace: Optional[Sequence[str]] = None)[source]¶ -
Thrown when frame target to be switched doesn’t exist.
-
args
¶
-
with_traceback
()¶ -
Exception.with_traceback(tb) –
set self.__traceback__ to tb and return self.
-
-
exception
selenium.common.exceptions.
NoSuchShadowRootException
(msg: Optional[str] = None, screen: Optional[str] = None, stacktrace: Optional[Sequence[str]] = None)[source]¶ -
Thrown when trying to access the shadow root of an element when it does
not have a shadow root attached.-
args
¶
-
with_traceback
()¶ -
Exception.with_traceback(tb) –
set self.__traceback__ to tb and return self.
-
-
exception
selenium.common.exceptions.
NoSuchWindowException
(msg: Optional[str] = None, screen: Optional[str] = None, stacktrace: Optional[Sequence[str]] = None)[source]¶ -
Thrown when window target to be switched doesn’t exist.
To find the current set of active window handles, you can get a list
of the active window handles in the following way:print driver.window_handles
-
args
¶
-
with_traceback
()¶ -
Exception.with_traceback(tb) –
set self.__traceback__ to tb and return self.
-
-
exception
selenium.common.exceptions.
ScreenshotException
(msg: Optional[str] = None, screen: Optional[str] = None, stacktrace: Optional[Sequence[str]] = None)[source]¶ -
A screen capture was made impossible.
-
args
¶
-
with_traceback
()¶ -
Exception.with_traceback(tb) –
set self.__traceback__ to tb and return self.
-
-
exception
selenium.common.exceptions.
SeleniumManagerException
(msg: Optional[str] = None, screen: Optional[str] = None, stacktrace: Optional[Sequence[str]] = None)[source]¶ -
Raised when an issue interacting with selenium manager occurs.
-
args
¶
-
with_traceback
()¶ -
Exception.with_traceback(tb) –
set self.__traceback__ to tb and return self.
-
-
exception
selenium.common.exceptions.
SessionNotCreatedException
(msg: Optional[str] = None, screen: Optional[str] = None, stacktrace: Optional[Sequence[str]] = None)[source]¶ -
A new session could not be created.
-
args
¶
-
with_traceback
()¶ -
Exception.with_traceback(tb) –
set self.__traceback__ to tb and return self.
-
-
exception
selenium.common.exceptions.
StaleElementReferenceException
(msg: Optional[str] = None, screen: Optional[str] = None, stacktrace: Optional[Sequence[str]] = None)[source]¶ -
Thrown when a reference to an element is now “stale”.
Stale means the element no longer appears on the DOM of the page.
- Possible causes of StaleElementReferenceException include, but not limited to:
-
- You are no longer on the same page, or the page may have refreshed since the element
was located. - The element may have been removed and re-added to the screen, since it was located.
Such as an element being relocated.
This can happen typically with a javascript framework when values are updated and the
node is rebuilt. - Element may have been inside an iframe or another context which was refreshed.
- You are no longer on the same page, or the page may have refreshed since the element
-
args
¶
-
with_traceback
()¶ -
Exception.with_traceback(tb) –
set self.__traceback__ to tb and return self.
-
exception
selenium.common.exceptions.
TimeoutException
(msg: Optional[str] = None, screen: Optional[str] = None, stacktrace: Optional[Sequence[str]] = None)[source]¶ -
Thrown when a command does not complete in enough time.
-
args
¶
-
with_traceback
()¶ -
Exception.with_traceback(tb) –
set self.__traceback__ to tb and return self.
-
-
exception
selenium.common.exceptions.
UnableToSetCookieException
(msg: Optional[str] = None, screen: Optional[str] = None, stacktrace: Optional[Sequence[str]] = None)[source]¶ -
Thrown when a driver fails to set a cookie.
-
args
¶
-
with_traceback
()¶ -
Exception.with_traceback(tb) –
set self.__traceback__ to tb and return self.
-
-
exception
selenium.common.exceptions.
UnexpectedAlertPresentException
(msg: Optional[str] = None, screen: Optional[str] = None, stacktrace: Optional[Sequence[str]] = None, alert_text: Optional[str] = None)[source]¶ -
Thrown when an unexpected alert has appeared.
Usually raised when an unexpected modal is blocking the webdriver
from executing commands.-
args
¶
-
with_traceback
()¶ -
Exception.with_traceback(tb) –
set self.__traceback__ to tb and return self.
-
-
exception
selenium.common.exceptions.
UnexpectedTagNameException
(msg: Optional[str] = None, screen: Optional[str] = None, stacktrace: Optional[Sequence[str]] = None)[source]¶ -
Thrown when a support class did not get an expected web element.
-
args
¶
-
with_traceback
()¶ -
Exception.with_traceback(tb) –
set self.__traceback__ to tb and return self.
-
-
exception
selenium.common.exceptions.
UnknownMethodException
(msg: Optional[str] = None, screen: Optional[str] = None, stacktrace: Optional[Sequence[str]] = None)[source]¶ -
The requested command matched a known URL but did not match any methods
for that URL.-
args
¶
-
with_traceback
()¶ -
Exception.with_traceback(tb) –
set self.__traceback__ to tb and return self.
-
-
exception
selenium.common.exceptions.
WebDriverException
(msg: Optional[str] = None, screen: Optional[str] = None, stacktrace: Optional[Sequence[str]] = None)[source]¶ -
Base webdriver exception.
-
args
¶
-
with_traceback
()¶ -
Exception.with_traceback(tb) –
set self.__traceback__ to tb and return self.
-