What is `NoSuchElementException` in Selenium-Python?

What is an exception?

An exception is an event that occurs during the execution of a program, that disrupts the normal flow of the program’s instructions.

Why does NoSuchElementException occur in Selenium?

When we try to find any element in an HTML page that does not exist, NoSuchElementException will be raised.

selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"css selector","selector":"[name="userNam"]"}

Possible reasons to debug

Below are some examples of scenarios that would raise an exception.

1. Change in source code of the webpage

It’s possible that the source code of the webpage may have been changed since the last time you accessed it. Change your code according to the new source to solve the issue.

2. Spelling error of the element

Cross-check the spelling of the element you want to find.

3. Invalid XPath

When new elements are added or deleted from the source code of the webpage, the XPath of that specific element also changes. Check XPath to determine if it is valid.

Demo

When we try to run the code below, it raises NoSuchElementException. This is because we try to find an element called userNam, but the webpage element name in the source code is userName.

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
import time
PATH=r"provide your chrome driver path here"
driver = webdriver.Chrome(PATH)
driver.get("http://demo.guru99.com/test/newtours/")
user_name = driver.find_element_by_name("userNam")
password = driver.find_element_by_name("password")
submit = driver.find_element_by_name("submit")
user_name.send_keys("mercury")
password.send_keys("mercury")
submit.click()

Handle exceptions

Script will terminate when an exception is raised. We can handle exceptions with the try except block and continue with the flow of the script.

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:\Users\GUTKRISH\chromedriver.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()