如何使用 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