使用 selenium python 从下拉选项中选择一个值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22524621/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Selecting a value from a drop-down option using selenium python
提问by
I want to select a value from a drop-down option. The html is as follows:
我想从下拉选项中选择一个值。html如下:
<span id="searchTypeFormElementsStd">
<label for="numReturnSelect"></label>
<select id="numReturnSelect" name="numReturnSelect">
<option value="200"></option>
<option value="250"></option>
<option value="500"></option>
<option selected="" value="200"></option>
<option value="800"></option>
<option value="15000"></option>
<option value="85000"></option>
</select>
</span
I tried as follows:
我试过如下:
find_element_by_xpath("//select[@name='numReturnSelect']/option[text()='15000']").click()
What is wrong with it? Please help me!
它有什么问题?请帮我!
采纳答案by Amith
Adrian Ratnapala is right and also i would choose idover name, so you can try the following :
阿德里安Ratnapala是正确的,也是我会选择id过name,所以你可以尝试以下方法:
find_element_by_xpath("//select[@id='numReturnSelect']/option[@value='15000']").click()
OR
或者
find_element_by_css_selector("select#numReturnSelect > option[value='15000']").click()
OR
或者
you can use select_by_value(value):
你可以使用select_by_value(value):
Select(driver.find_element_by_css_selector("select#numReturnSelect")).select_by_value(15000).click()
Click here for more info on Select.
单击此处了解更多信息Select。
回答by Kuladip
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)
select.select_by_visible_text('Visible Text')
select.select_by_value('value')
It will work fine
它会正常工作

