2016-12-06 52 views
0

我想使用Selenium & Python从选择字段中选择一个选项。如何使用Selenium和Python从下拉列表中选择一个值

的HTML如下:

<select autocomplete="off" class="style_input_item" name="AccountEnable" id="Enable" value="0" onchange="onPageDataChange()"> 
    <option value="0" selected="selected"><script>T("Disabled")</script>Disabled</option> 
    <option value="1"><script>T("Enabled")</script>Enabled</option> 
</select> 

,我尝试如下:

driver.find_element_by_xpath('//*[@id="Enable"]/option[value="1"]').click() 

我收到的错误:

selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//*[@id="Enable"]/option[value="0"]"}

+0

[硒 - Python的 - 下拉菜单选项的值]的可能的复制(HTTP:// stackoverflow.com/questions/7867537/selenium-python-drop-down-menu-option-value)。接受的答案并不是最好的方法。最好的方法是alecxe的答案。另见http://sqa.stackexchange.com/questions/1355/what-is-the-correct-way-to-select-an-option-using-seleniums-python-webdriver。 – JeffC

+0

接受的答案不是最好的方法。最好的方法是alecxe的答案。另见http://sqa.stackexchange.com/questions/1355/what-is-the-correct-way-to-select-an-option-using-seleniums-python-webdriver。 – JeffC

回答

0

试试看:

mydriver.find_element_by_xpath('//*[@id="Enable"]/option[@value="1"]').click() 

mydriver.find_element_by_xpath('//*[@id="Enable"]/option[2]').click() 
0

请确保您有选择:

from selenium.webdriver.support.select import Select 

然后

select = Select(driver.find_element_by_id('Enable')) 
select.select_by_index(0) 
相关问题