Home > Software design >  How to use if statement with selenium python?
How to use if statement with selenium python?

Time:02-26

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

CodePudding user response:

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

CodePudding user response:

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
  • Related