无法使用select选择下拉选项:UnexpectedTagNameException selenium:python

时间:2014-12-30 21:44:34

标签: python selenium python-3.x selenium-webdriver

如果我犯了非常基本的错误,我很抱歉,我还是新学习webdriver和python。

我正在尝试使用Select Class of python从下拉列表中选择一个选项,但我收到了意外的TagName异常。 标签上没有ID,因此我无法使用除类或属性之外的任何其他方法检测它。

HTML代码:

<div class="select-pixels-container ng-scope">
    <div class="action group">
    <table class="org-agency-advertiser">
    <tbody style="background-color: transparent;">
        <tr style="background-color: transparent;">
        <tr>
            <td style="background-color: transparent;">
                <select class="mm-select ng-valid localytics-chosen ng-dirty" ng-disabled="disabled('organizations')" ng-options="org.id as org.name for org in logic.organizations | orderBy:'name'" ng-model="logic.organization" chosen="" style="display: none;" data-placeholder="Select an Option">
                <div class="chosen-container chosen-container-single" style="width: 175px; background-color: transparent;" title="">
                    <a class="chosen-single" tabindex="-1" style="background-color: transparent;">
                        <span style="background-color: transparent;">Select</span>
                        <div>
                    </a>
                    <div class="chosen-drop">
                        <div class="chosen-search">
                            <input type="text" autocomplete="off">
                        </div>
                        <ul class="chosen-results">
                            <li class="active-result" style="" data-option-array-index="0">Select</li>
                            <li class="active-result" style="" data-option-array-index="1">1-800 Hnunagk 100278</li>
                            <li class="active-result result-selected" style="" data-option-array-index="2">10tc Tatgaa 100179</li>

我为此部分编写的代码是:

self.driver.find_element_by_css_selector("tbody>tr>td>div>a.chosen-single").click()
select=Select(self.driver.find_element_by_css_selector("tbody>tr>td>div>a[tabindex='-1']"))
select.select_by_index(0)

我得到的例外是

selenium.common.exceptions.UnexpectedTagNameException: Message: Select only works on <select> elements, not on <a>`

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

尚未共享所有HTML代码,但基本思路应如下:

self.driver.find_element_by_xpath('//*[@class="chosen-single"]').click()
listItems = self.driver.find_element_by_xpath('//div[@class="chosen-drop"]/ul/li')

for item in listItems: # <li> tags list
    if item.get_attribute("data-option-array-index") == "0": # select index 
        item.click() # if index=0 click
        break