2016-12-06 54 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) 
相關問題