Home > Enterprise >  Selenium : Get a div that contains a specific div class inside it
Selenium : Get a div that contains a specific div class inside it

Time:07-06

I have a page structure which contains a classname assigned to multiple divs. But there is one specific div that will contain a specific div.class inside it which happens dynamically.

<div >
   <div >
     <div >
       <div >
       </div>
     </div>
   </div>
   <div >
     <p >50 g</p>
     <div >
       ₹111 
       <span >
         ₹345
       </span>
     </div>
   </div>
</div>

If you see here this class ProductVariants__RadioButtonInner-sc-1unev4j-6 fgFqYM Line number 4 will be contained within one that specific class. Though there could be multiple of ProductVariants__VariantCard-sc-1unev4j-3 bEuNss.

How do I get the class ProductVariants__VariantCard-sc-1unev4j-3 bEuNss which contains ProductVariants__RadioButtonInner-sc-1unev4j-6 fgFqYM inside it.

This is what I have tried

driver.find_element(by=By.XPATH, value="//div[contains(@class,'ProductVariants__VariantCard-sc-1unev4j-3 bEuNss')]//div[contains(@class, 'ProductVariants__RadioButtonInner-sc-1unev4j-6 fgFqYM')]")

But this instead gives me the inner div and not the whole outer div

'<div ></div>'

CodePudding user response:

To identify the <div> with ProductVariants__RadioButtonInner-sc-1unev4j-6 fgFqYM you can use the following Locator Strategy:

driver.find_element(by=By.XPATH, value="//div[starts-with(@class, 'ProductVariants__RadioButtonInner')]//ancestor::div[starts-with(@class, 'ProductVariants__VariantCard')]")

CodePudding user response:

If you want to select ancestor node that contain specific descendant node try

driver.find_element(by=By.XPATH, value="//div[contains(@class,'ProductVariants__VariantCard-sc-1unev4j-3 bEuNss') and .//div[contains(@class, 'ProductVariants__RadioButtonInner-sc-1unev4j-6 fgFqYM')]]")
  • Related