首页 > 解决方案 > Unable to select dropdown with search box in selenium

问题描述

Dropdown box HTML:

<span class="select2-selection select2-selection--single" role="combobox" 
aria-haspopup="true" aria-expanded="false" tabindex="0" aria-labelledby="select2-country-container">
<span class="select2-selection__rendered" id="select2-country-container" title=""
</span>
<span class="select2-selection__arrow" role="presentation"><b role="presentation"></b>
</span>
</span>

For dropdown option Denmark=>

<li class="select2-results__option select2-results__option--highlighted" role="treeitem" aria-selected="false">Denmark</li>

I am unable to select the dropdown by Select class as there no Select is present. How to select the dropdown and how to search in the searchbox ?

enter image description here

标签: seleniumselenium-webdriver

解决方案


您必须单击下拉菜单以展开它,然后单击您希望选择的选项,使用 XPath 或 CSS 等选择器,而不是使用选择类。

以下是我Denmark从您提供的下拉列表中选择选项的方法:

# click combobox to expand it
driver.find_element_by_xpath("//span[@role='combobox']").click()

# wait for "Denmark" option to appear
denmark_option = WebDriverWait(driver, 10).until(
        EC.presence_of_element_located((By.XPATH, "//li[text()='Denmark']")))

# select the "Denmark" option
denmark_option.click()

推荐阅读