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

例如:

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


当前回答

首先你需要导入Select类,然后你需要创建Select类的实例。 创建Select类的实例后,可以在该实例上执行选择方法,从下拉列表中选择选项。 下面是代码

from selenium.webdriver.support.select import Select

select_fr = Select(driver.find_element_by_id("fruits01"))
select_fr.select_by_index(0)

其他回答

Selenium提供了一个方便的Select类来使用Select ->选项结构:

from selenium import webdriver
from selenium.webdriver.support.ui import Select

driver = webdriver.Firefox()
driver.get('url')

select = Select(driver.find_element_by_id('fruits01'))

# select by visible text
select.select_by_visible_text('Banana')

# select by value 
select.select_by_value('1')

参见:

使用Selenium的Python WebDriver的正确方法是什么?

首先你需要导入Select类,然后你需要创建Select类的实例。 创建Select类的实例后,可以在该实例上执行选择方法,从下拉列表中选择选项。 下面是代码

from selenium.webdriver.support.select import Select

select_fr = Select(driver.find_element_by_id("fruits01"))
select_fr.select_by_index(0)

我希望这段代码对您有所帮助。

from selenium.webdriver.support.ui import Select

带有id的下拉元素

ddelement= Select(driver.find_element_by_id('id_of_element'))

使用xpath的下拉元素

ddelement= Select(driver.find_element_by_xpath('xpath_of_element'))

下拉元素与CSS选择器

ddelement= Select(driver.find_element_by_css_selector('css_selector_of_element'))

从下拉菜单中选择“Banana”

使用下拉索引

ddelement.select_by_index (1)

使用下拉列表的值

ddelement.select_by_value (' 1 ')

您可以使用匹配下拉菜单中显示的文本。

ddelement.select_by_visible_text(香蕉)

我用它进行所有的点击和选择,它总是有效的。对于下拉项,只需确保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()

除非您的单击触发了某种ajax调用来填充列表,否则实际上不需要执行单击。

只需找到元素,然后枚举选项,选择您想要的选项。

这里有一个例子:

from selenium import webdriver
b = webdriver.Firefox()
b.find_element_by_xpath("//select[@name='element_name']/option[text()='option_text']").click()

你可以阅读更多: https://sqa.stackexchange.com/questions/1355/unable-to-select-an-option-using-seleniums-python-webdriver