如何使用硒设置亚马逊产品页面的大小?

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

我制作了一个 python 程序,我想将产品尺寸设置为点击添加到购物车按钮。所以为了启用我应该设置大小。如何使用硒键设置大小?另外,我希望此程序适用于不需要设置尺寸的产品,此程序适用于此类产品(例如 this product

所以我想设置尺寸以启用添加到购物车。代码应该在这一行之后(driver.get(url))。我附上了程序。我将不胜感激任何帮助。

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:\Users\Andrei\Downloads\chromedriver_win32\chromedriver.exe",
                          chrome_options=chrome_options)
driver.get(url)

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

要设置所需的大小,您可以使用 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()

您可以直接通过id获取商品尺码,但首先您需要点击尺码菜单

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()

检查页面上是否有您可以添加的菜单

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()