Home > Mobile >  How to click on the checkbox in reference to the text using Selenium Python
How to click on the checkbox in reference to the text using Selenium Python

Time:08-19

I'm trying to access a checkbox which is contained within an element as shown below.

enter image description here

I cannot identify using xpath as the order of these elements can change during development. Id is also out of bounds because the developer has implemented a plain ascending order for id like item-0, item-1 etc, meaning, the id would change depending on the order of elements on the page. So I'd like to identify the text Flexibel and using this element tick the associated checkbox. Is there a way to do that?

The element hierarchy upon inspection is given below

<div _ngcontent-adp-c61=""  id="item-6">
 <div _ngcontent-adp-c61="" >
  <input _ngcontent-adp-c61="" type="checkbox"  style="z-index: 2;">
  <!---->
  <div _ngcontent-adp-c61=""  style="cursor: pointer;">
   <div _ngcontent-adp-c61="" >
    <div _ngcontent-adp-c61="" ><img _ngcontent-adp-c61="" alt=""  style="padding: 1px;" src="assets/ces/time-model/TimeModelType-TimeInterval.svg">
     <div _ngcontent-adp-c61="" >
      <!---->
     </div>
    </div>
   <!---->
   <div _ngcontent-adp-c61="" >
    <div _ngcontent-adp-c61="" ><h5 _ngcontent-adp-c61="" ><span _ngcontent-adp-c61="" >Flexibel</span></h5><!---->
    </div>
    <p _ngcontent-adp-c61="" >allowed working hours for PQS team members</p>
    <!---->
   </div>
  </div>
  <div _ngcontent-adp-c61="" ><div _ngcontent-adp-c61="" ><i _ngcontent-adp-c61="" ></i><!----> Bearbeiten </div></div>
   <!---->
  </div>
  <!---->
 </div>
</div>

Thanks!

CodePudding user response:

The desired element is a Angular element, so to click on the element with respect to the text Flexibel you need to induce WebDriverWait for the element_to_be_clickable() and you can use the following locator strategy:

  • Using XPATH and ancestor:

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//span[@class='text-dark' and text()='Flexibel']//ancestor::div[contains(@class, 'card border shadow-none')]//input"))).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
    
  • Related