我需要从下拉菜单中选择一个元素。

例如:

<select id="fruits01" class="select" name="fruits">
  <option value="0">Choose your fruits:</option>
  <option value="1">Banana</option>
  <option value="2">Mango</option>
</select>

1)首先我得点击它。我是这样做的:

inputElementFruits = driver.find_element_by_xpath("//select[id='fruits']").click()

2)之后,我必须选择好的元素,让我们说芒果。

我尝试用inputElementFruits.send_keys(…)来做,但它不起作用。


当前回答

你不需要点击任何东西。 使用xpath或其他你选择的查找方法,然后使用发送键

举个例子: HTML:

<select id="fruits01" class="select" name="fruits">
    <option value="0">Choose your fruits:</option>
    <option value="1">Banana</option>
    <option value="2">Mango</option>
</select>

Python:

fruit_field = browser.find_element_by_xpath("//input[@name='fruits']")
fruit_field.send_keys("Mango")

就是这样。

其他回答

你可以很好地使用css选择器组合

driver.find_element_by_css_selector("#fruits01 [value='1']").click()

将attribute = value css选择器中的1更改为所需水果对应的值。

通过这种方式,您可以在下拉菜单中选择所有选项。

driver.get("https://www.spectrapremium.com/en/aftermarket/north-america")

print( "The title is  : " + driver.title)

inputs = Select(driver.find_element_by_css_selector('#year'))

input1 = len(inputs.options)

for items in range(input1):

    inputs.select_by_index(items)
    time.sleep(1)

在看了很多类似这篇文章之后,我设法想出了一个解决方案,让我可以在下拉列表中选择一个项目。我尝试了.send_keys,单击()和选择在各种方式没有成功。最后,在单击下拉列表中的项目之前,向下拉列表发送了3次click()命令。

dropMenu = browser.find_element_by_id('cmbDeviceType')
dropMenu.click()
dropMenu.click()
dropMenu.click()

deviceType = browser.find_element_by_id('cmbDeviceType_DDD_L_LBI16T0')
deviceType.click()

绝对不是很漂亮,但是很好用。

希望这能帮助到一些人。这是在Firefox 88.0.1上使用Python3.7.7完成的。

以下方式您可以在下拉框中选择。

select=browser.find_element(by=By.XPATH,value='path to the dropdown')
 select.send_keys("Put value here to select it")
from selenium.webdriver.support.ui import Select
driver = webdriver.Ie(".\\IEDriverServer.exe")
driver.get("https://test.com")
select = Select(driver.find_element_by_xpath("""//input[@name='n_name']"""))
select.select_by_index(2)

它会正常工作的