Home > other >  Unable to click label that doesn't have any text using Python and Selenium
Unable to click label that doesn't have any text using Python and Selenium

Time:02-20

I'm trying to click the label below.

Label html:

<div >
  <input id="entradas-checkbox-condiciones" type="checkbox" >
  <label style="padding-left:1rem;">

I've tried clicking the label with this code:

WebDriverWait = wait

label1 = wait(self.driver, 10).until(EC.presence_of_all_elements_located((By.XPATH, "//*[@class = 'is-inline-block']")))[3]
label1.find_element_by_xpath('//label[style="padding-left:1rem;"]').click()

But i get the following error:

selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element:

Can somebody help me with the code? Thanks in advance.

CodePudding user response:

To locate and invoke click() on the clickable element instead of presence_of_element_located() you need to induce WebDriverWait for the element_to_be_clickable() and you can use either of the following locator strategies:

  • Using CSS_SELECTOR:

    WebDriverWait(self.driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "div.is-inline-block input.switch.is-rounded.is-small#entradas-checkbox-condiciones"))).click()
    
  • Using XPATH:

    WebDriverWait(self.driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//div[@class='is-inline-block']//input[@class='switch is-rounded is-small' and @id='entradas-checkbox-condiciones']"))).click()
    
  • Note : You have to add the following imports :

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

References

You can find a couple of relevant discussions on NoSuchElementException in:

  • Related