1

I'm trying to create an if statement with python selenium. I want if there is some element do something, but if there is no element pass, but it's not working.

I tried like this, but how do I write if this element is available continue, but if not pass.

if driver.find_element_by_name('selectAllCurrentMPNs'):
    #follow some steps...
else:
    pass

EDIT

It doesn't find element and crashes, but it should pass.

selenium.common.exceptions.NoSuchElementException: Message: Unable to locate element: [name="selectAllCurrentMPNs"]
Stacktrace:
WebDriverError@chrome://remote/content/shared/webdriver/Errors.jsm:183:5
NoSuchElementError@chrome://remote/content/shared/webdriver/Errors.jsm:395:5
element.find/</<@chrome://remote/content/marionette/element.js:300:16
5
  • define 'not working' Commented Feb 25, 2022 at 1:01
  • It runs this line driver.find_element_by_name('selectAllCurrentMPNs') and quit whole process. In this case it should pass. Commented Feb 25, 2022 at 1:06
  • if there any error then paste here. i don't think it will exit silently. Commented Feb 25, 2022 at 1:07
  • Check the EDIT in question. Commented Feb 25, 2022 at 1:10
  • 1
    normally you can use try catch block, in catch, you can do pass stuffs. Commented Feb 25, 2022 at 1:12

2 Answers 2

3

You can tackle this situation with find_elements as well.

find_elements

will return a list of web element if found, if not then it won't throw any error instead size of the list will be zero.

try:
    if len(driver.find_elements(By.NAME, "selectAllCurrentMPNs")) > 0:
        #follow some steps...
    else:
        #do something when `selectAllCurrentMPNs` web element is not present.
except:
    pass
Sign up to request clarification or add additional context in comments.

2 Comments

can i conclude find_elements(By is a new version implementaion that not throw exceptions if not found?
@LeiYang: Yes, it's been there for quite a while now.
1

Use a WebDriverWait to look for the element.

from selenium.common import exceptions
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC




try:
    item = WebDriverWait(driver, 15).until(EC.presence_of_element_located((By.NAME, "selectAllCurrentMPNs")))
    #do something with the item...
except TimeoutException as e:
    print("Couldn't find: " + str("selectAllCurrentMPNs"))
    pass

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.