Home > Software engineering >  Python Selenium, find certain elements under a certain element
Python Selenium, find certain elements under a certain element

Time:09-02

<section id='browse-search'>
  <div>
      <div>
          <div>
                <div class='product-pod'>
                <div class='product-pod>'>
          </div>
      </div>
  </div>
</section>
<div class='product-pod>'>
<div class='product-pod>'>

I have a webpage like this structure. and I need a cleaner way to locate elements with class='product-pod'. driver.find_elements(By.XPATH,"div[@class='product-pod']") will not work, because there are a few matched elements outside the section element.

Please advise what is the most appropriate way to locate those elements.

CodePudding user response:

With what you have provided, this strategy could be built:

if the extra > that you provided is a typo, then:

For first div element:

driver.find_element(By.XPATH, "(//section[@id='browse-search']//div[@class='product-pod'])[1]")

For second div element:

driver.find_element(By.XPATH, "(//section[@id='browse-search']//div[@class='product-pod'])[2]")

If the > is not a typo, then the structure changes, and the below strategies would work:

For main div element:

driver.find_element(By.XPATH, "//section[@id='browse-search']//div[@class='product-pod']")

For inner div element:

driver.find_element(By.XPATH, "//section[@id='browse-search']//div[@class='product-pod']/div")

CodePudding user response:

you can try xpath like

   //section[@id='browse-search']//div[contains(@class,'product-pod')]

which will collect all product-pod classes inside section having id = browse-search

  • Related