Home > Software design >  How can I check if an element is available, then click it?
How can I check if an element is available, then click it?

Time:10-24

i just want the while statement displayed and selenium clicks selenium have to follow the below code, Thank you in advance.

while (driver.find_element(By.CLASS_NAME, 'area is-available').click()):
           driver.find_element(By.XPATH, '/html/body/div[3]/div[1]/div/div/article[1]/div/section[2]/label[2]/div[2]/span').click()
           time.sleep(4)

CodePudding user response:

From what I've gathered, you're trying to check if the element is shown, your attempt was close, but not proper.

Here is the proper way to check if an element exists, then click it. Only using your method.

from selenium.common.exceptions import NoSuchElementException 

def check_element_exists_by_class_name(fullClassName):
    try:
       driver.find_element(By.CLASS_NAME, fullClassName)
       return True
    except NoSuchElementException:
           return False 
    return True

while check_element_exists_by_clas_name('') == False:
      pass

driver.find_element(By.XPATH, '').click()

CodePudding user response:

As per my understanding, you want to check if an element exists and if it does than you want to click on another element, right?

You can use NoSuchElementException to find if the element exists or not. Then, you run the result into a while loop.

From my understanding, your code should look something like this:

from selenium.common.exceptions import NoSuchElementException        

def check_element():
    try:
        driver.find_element(By.CLASS_NAME, 'area is-available')
        return True
    except NoSuchElementException:
        return False
                
while check_element():
    driver.find_element(By.XPATH, '/html/body/div[3]/div[1]/div/div/article[1]/div/section[2]/label[2]/div[2]/span').click()
    time.sleep(4)
  • Related