Search code examples
pythonseleniumautomationselenium-chromedriverfindelement

Grab and Click Button using Selenium Python


There are several size options under 'SELECT SIZE' on this site: https://www.myntra.com/sports-shoes/puma/puma-men-black-eternity-nitro-running-shoes/14521968/buy

I have been trying to somehow click one button to choose size of the shoes using python selenium but every time it says "no such element: unable to locate element:.....".Here's what I have tried till now.

size_button = self.find_element(
            By.CSS_SELECTOR,
            'button[class="btn default outline   size-btn big selected"]'
        )
size_button = self.find_element(
            By.CSS_SELECTOR,
            'ul[class="sizes-list list-unstyled list-inline padding-md-left padding-md-bottom"]'
        )
size_button = self.find_element(
            By.XPATH,            '/html/body/div[2]/div/div[2]/div[2]/div[2]/div/div[2]/div[1]/div/div/div[4]/div[6]/div[2]/div[1]/div[2]/ul/li[1]/button'
        )
size_button = self.find_element(
            By.XPATH,           '//[@id="reactPageContent"]/div/div/div[4]/div[6]/div[2]/div[1]/div[2]/ul/li[1]/button'
        )

Here's the error for one of the above code:

selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"css selector","selector":"button[class="btn default outline   size-btn big selected"]"}

Solution

  • For click on buttons this code may help you

    from selenium import webdriver
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC
    
    import time
    
    from selenium.webdriver.support.wait import WebDriverWait
    
    if __name__ == '__main__':
        options = webdriver.ChromeOptions()
        driver = webdriver.Chrome(executable_path="chromedriver", chrome_options=options)
    
        driver.get('https://www.myntra.com/sports-shoes/puma/puma-men-black-eternity-nitro-running-shoes/14521968/buy')
    
        # get all buttons by common class
        buttons = driver.find_elements(By.CLASS_NAME, 'size-buttons-size-button')
    
        # wait for first button (buttons[0]) be clickable and click
        WebDriverWait(driver, 20).until(EC.element_to_be_clickable(buttons[0])).click()
        time.sleep(3)
        
        # clicking in all buttons
        for button in buttons:
            WebDriverWait(driver, 20).until(EC.element_to_be_clickable(button)).click()
            time.sleep(3)
    
        driver.quit()
    

    note1: you can use for example buttons[0].click() but the button may not loaded, giving for you a error

    note2: in this example i used the class as selector but you have countless selector options (in future, with more experience, you will be able to choose the clearest selector!)