Selenium properly clicks on the correct option, but when selecting the element for add to cart, it always adds only the first option

Question:

I’m creating a webscraper with Selenium that will add products to a cart, and then cycle through cities, states and zip codes to give me the total cost of shipping + taxes for each area.

The website I’m using is: https://www.power-systems.com/shop/product/proelite-competition-kettlebell

Everything in my code appears to be working normally – the window will open, close a few pop ups and I can see Selenium select the proper option. However, regardless of whatever I’ve tried, after selenium clicks the "Add to Cart" button, it always adds the first option, despite having selected the proper one

Here is what I have been trying:

#created to simplify the code since I'll be using this option often
def element_present_click1(path_type,selector):
    element_present = EC.element_to_be_clickable((path_type , selector))
    WebDriverWait(driver, 30).until(element_present)
    try:
        driver.find_element(path_type , selector).click()
    except:
        clicker = driver.find_element(path_type , selector)
        driver.execute_script("arguments[0].click();", clicker)


path = "C:Program Files (x86)msedgedriver.exe"
driver = webdriver.Edge(path)
driver.get('https://www.power-systems.com/shop/product/proelite-competition-kettlebell')
    

element_present_click1(By.CSS_SELECTOR,'button[name="bluecoreCloseButton"]')
element_present_click1(By.CSS_SELECTOR,'a[id="hs-eu-decline-button"]')


###this will correctly select the proper element
element_present_click1(By.XPATH, f"//span[text()='32 kg']")


###after this is clicked, it will always add the first option, which is 8 kg
driver.find_element(By.CSS_SELECTOR,'button.btn.btn-primary.add-to-cart.js-add-to-cart-button').submit()

I’ve tried a few different things, adding in some time.sleep() after clicking the option, refreshing the browser page, or selecting the option twice – no matter what I try, when I click add to cart it always adds the first option

Is there something I’m missing? Any help would be appreciated

Asked By: pedro flores

||

Answers:

You are using a wrong selector in the last step.
button.btn.btn-primary.add-to-cart.js-add-to-cart-button is not a unique locator.
You need to click the button inside the selected element block.
This will work:

driver.find_element(By.CSS_SELECTOR, ".variant-info.selected .add-to-cart-rollover").click()
Answered By: Prophet

It looks to me that find_element returns ONLY the first element it can find. Having taken a look at find_element it looks like you’d want to replace

driver.find_element(By.CSS_SELECTOR,'button...').submit()

with

random.choice(driver.find_elements(By.CSS_SELECTOR,'button...')).submit()
Answered By: Jelmergu