How to set the size for Amazon product page using selenium?

Question:

I made a python program and I would like to set the size of the product to click on the add to cart button. So to enable I should set the size. How can I set the size using selenium keys? Also, I would like this program to work for products that don’t require to set the size, this program is working for this kind of products(for example this product)

So I would like to set the size to enable add to cart. The code should be after this line (driver.get(url)). I attached the program. I will appreciate any help.

from selenium import webdriver
from time import sleep
from selenium.webdriver.common.keys import Keys

proxies = {
    'http': 'http://217.119.82.14:8080',
    'https': 'http://196.27.107.30:8080',
}

url = "https://www.amazon.com/Disney-Stitch-Surfer-Adult-T-shrt/dp/B072VPQ1BG/ref=sr_1_4?ie=UTF8&qid=1517916607&sr=8-4&keywords=t+shrt"

chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--proxy-server=%s' % proxies)

driver = webdriver.Chrome(executable_path="C:\UsersAndreiDownloadschromedriver_win32chromedriver.exe",
                          chrome_options=chrome_options)
driver.get(url)

driver.find_element_by_xpath('//*[@id="submit.add-to-cart"]/span/input').click()
Asked By: ryy77

||

Answers:

To set required size you can use Select class:

from selenium.webdriver.support.ui import Select
from selenium.webdriver.support.ui import WebDriverWait as wait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By

driver.get(url)
# Create new object for drop down
select = Select(driver.find_element_by_id("native_dropdown_selected_size_name"))
# Select "Small" size
select.select_by_visible_text("Small")
wait(driver, 5).until(EC.element_to_be_clickable((By.XPATH, '//input[@id="add-to-cart-button" and not(@style="cursor: not-allowed;")]'))).click()
Answered By: Andersson

You can get the item size directly by the id, but first, you need to click on the size menu

sizemenu = driver.find_element_by_id('dropdown_selected_size_name')
sizemenu.click()
select = driver.find_element_by_id('size_name_1') #Medium size
select.click()

to check if there is a menu on the page you can add

if driver.find_element_by_id('dropdown_selected_size_name') != 0:

if driver.find_element_by_id('dropdown_selected_size_name') != 0:
    sizemenu = driver.find_element_by_id('dropdown_selected_size_name')
    sizemenu.click()

    sleep(5)   

    select = driver.find_element_by_id('size_name_1') #medium size
    select.click()
    print("select size")
else:
    print("do nothing")


sleep(5)    
button = driver.find_element_by_id('submit.add-to-cart')
button.click()
Answered By: Guilherme