Targeting DOM elements from parent to grand parent produces different result

Viewed 29

I am using selenium to target 3 buttons as in the image below

enter image description here

Here is the code for each thumbnail

<div class="product">
    <div class="product-image">
        <img src="./images/raspberry.jpg" alt="Raspberry - 1/4 Kg">
    </div>
    <h4 class="product-name">Raspberry - 1/4 Kg</h4>
    <p class="product-price">160</p>
    <div class="stepper-input">
        <a href="#" class="decrement">–</a>
        <input type="number" class="quantity" value="1">
        <a href="#" class="increment">+</a>
    </div>
    <div class="product-action">
        <button class="" type="button">ADD TO CART</button>
    </div>
</div>

When I try the following code below it fulfills the goal of clicking the 3 buttons

add_cart_btn_locator = (By.CSS_SELECTOR, "div[class='product'] button")
add_cart_btn_link = driver.find_elements(*add_cart_btn_locator)

for i in add_cart_btn_link:
    i.click()

But when I try to change my selector to div[class='product-action'] button, only the first button is clicked then the below error appears

Message: stale element reference: element is not attached to the page document

May I kindly ask what is the difference of the two locators and why they do not work identically?

1 Answers

change your loop :

add_cart_btn_locator = (By.CSS_SELECTOR, "div[class='product-action'] button")
add_cart_btn_link = driver.find_elements(*add_cart_btn_locator)
nbrlinks = len(add_cart_btn_link)
for i in range(nbrlinks):
    add_cart_btn_locator = (By.CSS_SELECTOR, "div[class='product-action'] button")
    add_cart_btn_link = driver.find_elements(*add_cart_btn_locator)
    add_cart_btn_link[i].click()

you have to reload the search of items each time

Related