如何使用Python使用Selenium选择下拉菜单值? [英] How to select a drop-down menu value with Selenium using Python?

查看:193
本文介绍了如何使用Python使用Selenium选择下拉菜单值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I need to select an element from a drop-down menu.

例如:

<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)首先,我必须单击它.我这样做:

1) First I have to click on it. I do this:

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

2)之后,我必须选择好元素,我们说Mango.

2) After that I have to select the good element, lets say Mango.

我试图用inputElementFruits.send_keys(...)来做到这一点,但是没有用.

I tried to do it with inputElementFruits.send_keys(...) but it did not work.

推荐答案

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

Unless your click is firing some kind of ajax call to populate your list, you don't actually need to execute the click.

只需找到元素,然后枚举选项,然后选择所需的选项即可.

Just find the element and then enumerate the options, selecting the option(s) you want.

这里是一个例子:

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/无法选择使用硒的python-webdriver选项

You can read more in:
https://sqa.stackexchange.com/questions/1355/unable-to-select-an-option-using-seleniums-python-webdriver

这篇关于如何使用Python使用Selenium选择下拉菜单值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆