4

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,

3
  • You could use try and except statements? Commented Aug 25, 2016 at 13:58
  • what probably happens is that driver.find_element_by_partial_link_text('Create Activity') returns None and the elem.is_displayed() throws a NoSuchElementException. There are many things you can do as for example: if elem: and then the if elem.is_displayed() or a try-except block Commented Aug 25, 2016 at 13:59
  • Best way to use find_elements and check size of elements instead of exception caching, see provided answer...:) Commented Aug 25, 2016 at 14:24

3 Answers 3

17

you can catch the exception and act accordingly:

try:
    elem = driver.find_element_by_partial_link_text('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!")
except NoSuchElementException:
    print("...")

Also, I would probably modify the test to make sure that the element is indeed "clickable":

if elem.is_displayed() and elem.is_enabled():
Sign up to request clarification or add additional context in comments.

Comments

10

find_element returns either element or throws NoSuchElementException, So for best way to determine element is present with if condition, You should try using find_elements instead of catching exception because it's returns either list of WebElement or empty list, so you just check its length as below :-

elems = driver.find_elements_by_partial_link_text('Create Activity')

if len(elems) > 0 and elems[0].is_displayed():
    elems[0].click()
    print("FOUND THE LINK CREATE ACTIVITY! and Clicked it!")
else: 
    print ("NO LINK FOUND")

Comments

-1

Even simpler than try/except is just use find_elements(). If not present, it will return empty list. If not empty, clink of first found: found[0].click()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.