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

例如:

<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(…)来做,但它不起作用。


当前回答

根据提供的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>

要从html-select菜单中选择<option>元素,必须使用select类。此外,当你必须与下拉菜单交互时,你必须为element_to_be_clickable()诱导WebDriverWait。

要从下拉菜单中选择<选项>,文本为Mango,你可以使用以下定位器策略之一:

Using ID attribute and select_by_visible_text() method: from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.support.ui import Select select = Select(WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.ID, "fruits01")))) select.select_by_visible_text("Mango") Using CSS-SELECTOR and select_by_value() method: select = Select(WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "select.select[name='fruits']")))) select.select_by_value("2") Using XPATH and select_by_index() method: select = Select(WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "//select[@class='select' and @name='fruits']")))) select.select_by_index(2)

其他回答

下拉菜单WITHOUT <select>

这适用于我每次面对没有<select>标签的下拉菜单

# Finds the dropdown option by its text
driver.find_element_by_xpath("//*[text()='text of the option']")

导入ActionChains模块

from selenium.webdriver.common.action_chains import ActionChains

使用ActionChains点击元素

drp_element = driver.find_element_by_xpath("//*[text()='text of the option']")
action = ActionChains(driver)
action.click(on_element=drp_element).perform()

它与选项值工作:

from selenium import webdriver
b = webdriver.Firefox()
b.find_element_by_xpath("//select[@class='class_name']/option[@value='option_value']").click()

我用它进行所有的点击和选择,它总是有效的。对于下拉项,只需确保xpath是您想要选择的实际值。

var = WebDriverWait(driver, explicit_wait_seconds).until(
        EC.element_to_be_clickable((By.XPATH, self)))
    # added the click here.
    ActionChains(driver).move_to_element(var).click()
    perform_actions()

actions.perform()
 # Reset was required to clear it. Might be patched now.
actions.reset_actions()
for device in actions.w3c_actions.devices:
    device.clear_actions()
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)

它会正常工作的

dropdown1 = Select(driver.find_element_by_name("fruits"))
dropdown1.select_by_visible_text('banana')