使用 Selenium 和 python 从下拉菜单中选择一个项目

Selecting an item from a dropdown menu with Selenium and python

我正在尝试开发一个“机器人”,以便在“zalando”网站上更快地进行购买。 例如,假设我想买这个:https://www.zalando.it/nike-sportswear-air-force-1-07-lv8-sneakers-basse-whiteblackwolf-grey-ni112o0m9-a11.html

我需要菜单中 select 鞋码的代码(检查 link 或下图),我尝试使用“Select”功能:

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.chrome.options import Options
from fake_useragent import UserAgent
from selenium.webdriver.support.ui import Select
 #The first thing you’ll want to do with WebDriver is navigate to a link.
#The normal way to do this is by calling get method:

options = Options()
ua = UserAgent()
userAgent = ua.random
print(userAgent)
options.add_argument(f'user-agent={userAgent}')

driver = webdriver.Chrome(options=options)
driver.get("https://www.zalando.it/nike-sportswear-air-force-1-07-lv8-sneakers-basse- 
whiteblackwolf-grey-ni112o0m9-a11.html")

#tried this
element = driver.find_element_by_xpath('/html/body/div[7]/div/div[3]')
all_options = element.find_elements_by_tag_name("_7Cm1F9 ka2E9k uMhVZi dgII7d _6yVObe 
pVrzNP")
for option in all_options:
  print("Value is: %s" % option.get_attribute("value"))
  option.click()

#and this:

#select = Select(driver.find_element_by_id('id'))
#select.deselect_all()

element = 
driver.find_element_by_xpath('/html/body/div[2]/div/div[1]/div/div/div[2]/div[1]/x- 
wrapper-re-1-6/div/div[2]').click

但是 Select 不起作用,我希望有人能向我解释原因。谢谢!

该网页的结构相当复杂,实际上并没有像您预期的那样使用 select 元素。

我总是先看看开发人员控制台的“元素”选项卡中的实际 html 结构,大小选择如下所示:

原则上您必须执行以下 3 个步骤:

找到打开尺码选择的元素

这似乎是用 ID 为 picker-triggerbutton 完成的,只需使用即可工作:

buttonElement = driver.find_element_by_id('picker-trigger')
buttonElement.click()

在尺寸 table

的外壳内找到合适的尺寸

table 本身可以使用名称为 name size-picker-form 的表单和使用具有特定文本的 span 来识别大小行:

sizeElement = driver.find_element_by_xpath('//form[@name="size-picker-form"]//span[text()="40"]')
sizeElement.click()

希望这对您有所帮助,或者至少为您指明了正确的方向。