All, I am in need of some serious " dumbed down " examples of how to write code in Python that will do something if a element is there or not there. I'm new to programing and I have reviewed a days worth of posts and I can't seem to figure it out....
Here is what I am trying to do.
from selenium.common.exceptions import NoSuchElementException, staleElementReferenceException
elem = driver.find_element_by_partial_link_text('Create Activity')
print("Searching for Create Activity.")
if elem.is_displayed():
elem.click() # this will click the element if it is there
print("FOUND THE LINK CREATE ACTIVITY! and Clicked it!")
else:
print ("NO LINK FOUND")
So, Providing that there is a LINK present that is element_by_partial_link_text('Create Activity')
I get the proper response ... Searching for Create Activity. FOUND THE LINK CREATE ACTIVITY! and Clicked it!
My problem is when there is NOT a link that Matches element_by_partial_link_text('Create Activity')
I don't get what I would expect that is in my else statement.
print ("NO LINK FOUND")
I get ...
Traceback (most recent call last): File "", line 1, in File "C:\Program Files (x86)\Python35-32\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 341, in find_element_by_partial_link_text return self.find_element(by=By.PARTIAL_LINK_TEXT, value=link_text) File "C:\Program Files (x86)\Python35-32\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 745, in find_element {'using': by, 'value': value})['value'] File "C:\Program Files (x86)\Python35-32\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 236, in execute self.error_handler.check_response(response) File "C:\Program Files (x86)\Python35-32\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 194, in check_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"partial link text","selector":"Create Activity"}
How do I get selenium within Python to turn this exception or error to not halt my script and just process the ELSE statement.
Thanks,
tryandexceptstatements?driver.find_element_by_partial_link_text('Create Activity')returnsNoneand theelem.is_displayed()throws aNoSuchElementException. There are many things you can do as for example:if elem:and then theif elem.is_displayed()or atry-exceptblockfind_elementsand check size of elements instead of exception caching, see provided answer...:)