How to continue if find_element does not find anything instead of producing an error that terminates the program?
Question:
I have the following code:
driver.find_element(By.XPATH, "/html/body/...").text
However, the element I am looking for is optional. It will sometimes be present and sometimes not. I want to keep track whether it is present. If it is not present, the code should not be terminated because driver.find_element throws a the NoSuchElementException
error. I want to code to continue.
Answers:
Use a
‘try: except NoSuchElementException:’ statement
You can use try..except block to ignore if element not present
try:
driver.find_element(By.XPATH, "/html/body/...").text
except:
pass
try
from selenium.common.exceptions import NoSuchElementException
try:
driver.find_element(By.XPATH, "/html/body/...").text
except NoSuchElementException:
#print('no element')
pass
Try this, only if elements with this xpath exists, get text, else continue:
if len(driver.find_elements(By.XPATH, "/html/body/...")) > 0:
driver.find_element(By.XPATH, "/html/body/...").text
...
Don’t catch the raw exception.
Instead handle the desired NoSuchElementException to prevent leakage of the flaky exceptions as follows:
try:
driver.find_element(By.XPATH, "/html/body/...").text
except NoSuchElementException:
pass
I have the following code:
driver.find_element(By.XPATH, "/html/body/...").text
However, the element I am looking for is optional. It will sometimes be present and sometimes not. I want to keep track whether it is present. If it is not present, the code should not be terminated because driver.find_element throws a the NoSuchElementException
error. I want to code to continue.
Use a
‘try: except NoSuchElementException:’ statement
You can use try..except block to ignore if element not present
try:
driver.find_element(By.XPATH, "/html/body/...").text
except:
pass
try
from selenium.common.exceptions import NoSuchElementException
try:
driver.find_element(By.XPATH, "/html/body/...").text
except NoSuchElementException:
#print('no element')
pass
Try this, only if elements with this xpath exists, get text, else continue:
if len(driver.find_elements(By.XPATH, "/html/body/...")) > 0:
driver.find_element(By.XPATH, "/html/body/...").text
...
Don’t catch the raw exception.
Instead handle the desired NoSuchElementException to prevent leakage of the flaky exceptions as follows:
try:
driver.find_element(By.XPATH, "/html/body/...").text
except NoSuchElementException:
pass