Skip to content
Advertisement

Selenium: Iterate through child elements with different class names

I want to iterate through child elements of parent . Access the child element, extract price information and move on to next child element.

Here is my code

pack_size_elements =  wd.find_elements(By.XPATH , "//div[@class='_1LiCn']/div")
for element in pack_size_elements:
    price = element.find_element(By.XPATH, "//span[@class ='_2j_7u']").text.strip()
    print(price)

Output:

Rs 61
Rs 61
Rs 61
Rs 61

Concern/What I want help with: Price output should change in each iteration as element changes. But I am only getting same price as first element price

Desired Output:

Rs 61
Rs 299.50
Rs 1797
Rs 1830

HTML outer element

HTML element

1st Child element

Ist child element

Advertisement

Answer

The following should work:

for element in pack_size_elements:
    price = element.find_element(By.XPATH, ".//span[@class ='_2j_7u']").text.strip()
    print(price)

By adding a dot before the //, you are searching within that element only.

Advertisement