Search code examples
pythonselenium-webdriverweb-scrapingselenium-chromedriver

How can I find a button element and click on it?


I am trying to click on a specific color then click buy button, I find color and can click on them, but buy element can not be found. I try some locator like XPATH, CSS_SELECTOR and others.

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time
driver = webdriver.Edge() 
driver.maximize_window()
driver.get("https://www.digikala.com/product/dkp-4645665/")  

try:
    main_div = WebDriverWait(driver, 10).until(
        EC.presence_of_element_located((By.CSS_SELECTOR, "div.flex.lg\\:flex-wrap.overflow-x-auto.px-5.lg\\:px-0"))
    )
    
    child_elements = main_div.find_elements(By.CSS_SELECTOR, "div.bg-neutral-000.flex.items-center\
                                            .justify-center.cursor-pointer.ml-2.px-2.lg\\:px-0.styles_InfoSectionVariationColor__pX_3M") 
    specific_value = "سفید" 

    add_to_cart= WebDriverWait(driver, 10).until(
        EC.presence_of_element_located((By.CSS_SELECTOR, "button[data-testid='add-to-cart']"))
    )
    for child in child_elements:
        time.sleep(1)
        if child.text == specific_value:
            add_to_cart.click()
            break

except Exception as e:
    print("Exception:", e)
finally:
    driver.quit()  

Solution

  • I rewrote and simplified your code. Since I'm assuming you might want to choose different colors, I wrote a method specifically to choose a color based on the colorName parameter.

    def select_color(colorName):
        WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, f"//div[./div[text()='{colorName}']]"))).click()
    

    Then the main script looks like

    from selenium import webdriver
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC
    from selenium.webdriver.support.wait import WebDriverWait
    
    url = 'https://www.digikala.com/product/dkp-4645665'
    driver = webdriver.Chrome()
    driver.maximize_window()
    driver.get(url)
    
    colorName = "آبی کاربنی"
    
    select_color(colorName)
    
    wait = WebDriverWait(driver, 10)
    wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "button[data-testid='add-to-cart']"))).click()
    # do other stuff
    

    This selects the provided color and adds the item to the cart.