Home > Enterprise >  Find items within <li> tags using Selenium
Find items within <li> tags using Selenium

Time:04-27

I've tried to find the element item (eg. Item1, Item2, Item3, and Item4) within the 'li' tag using Selenium, but an error happened with this message:

no such element: Unable to locate element

How do I find the items within the 'li' tag element?

elms = driver.find_element(by=By.CLASS_NAME, value='product-list')

or

elms = driver.find_element(by=By.XPATH, value="//*[@id='product-list']") 

Web source:


<div class='product'> 
 <div class='menuList1'> Menu1 Menu2</div>
 <div class='menuList2'> aaa </div>
 <ul id='productDetail' class='product-list'> 
  <li class='product-list detail' id='1'> Item1</li> 
  <li class='product-list detail' id='2'> Item2</li> 
  <li class='product-list detail' id='3'> Item3</li> 
  <li class='product-list detail' id='4'> Item4</li> 
 </ul>
</div>

CodePudding user response:

The locator strategies you have tried were a bit errorprone. The desired elements are within <li> having class attribute as product-list detail

<div class='product'> 
    <div class='menuList1'> Menu1 Menu2</div>
    <div class='menuList2'> aaa </div>
         <ul id='productDetail' class='product-list'> 
              <li class='product-list detail' id='1'> Item1</li> 
              <li class='product-list detail' id='2'> Item2</li> 
              <li class='product-list detail' id='3'> Item3</li> 
              <li class='product-list detail' id='4'> Item4</li> 
         </ul>
    </div>

Solution

To find the elements within the <li> tags you can use either of the following locator strategies:

  • Using css_selector:

    elms = driver.find_elements(By.CSS_SELECTOR, "div.product div.menuList2 > ul.product-list li.product-list.detail")
    
  • Using xpath:

    elms = driver.find_elements(By.XPATH, "//div[@class='product']//div[@class='menuList2']/ul[@class='product-list']//li[@class='product-list detail']")
    

CodePudding user response:

You can use list of elements:

elements = driver.find_elements(by=By.XPATH, value="//li[@class='product-list detail']")

for e in elements:
    print(e.text)

  • Related