首页 > 解决方案 > Selenium - 如何从下拉菜单中选择一个值

问题描述

我是 selenium 的新手,我试图从下拉菜单中获取一个值,特别是在我打开菜单后,我想为鞋码选择“40”。这是html代码

https://i.postimg.cc/Bn3Nhv26/codicehtml.png

我尝试使用此代码,但它没有得到元素:

driver.find_element_by_xpath("//label[@class='_6G4BGa _6yVObe _7Cm1F9 ka2E9k uMhVZi FxZV-M sgIQH4 OXMl2N oW5DLR JT3_zV ZkIJC- Md_Vex JCuRr_ UTtITa _0xLoFW FCIprz pVrzNP KRmOLG NuVH8Q' and @for='size-picker-NI111A0ZB-A110085000']").click()

我还尝试考虑一种不同的方法,因为我希望代码适用于所有项目,首先从菜单中获取所有选项,然后选择我想要的选项,但是在我得到值之后我不知道如何继续

标签: pythonselenium

解决方案


尝试以下模式:

from selenium.webdriver.support.select import Select

# `dropdown_id` is the HTML id of the dropdown input
selector = Select(driver.find_element_by_xpath(r"//*[@id='%s']" % dropdown_id)
# `value` is the value of the option in the dropdown you want to select
selector.select_by_value(value)

请注意,您可能必须等到使用WebDriverWaitwith加载元素visibility_of_element_located


推荐阅读