Select a dropdown using Python + Selenium

ⅰ亾dé卋堺 提交于 2019-12-13 01:34:47

问题


I am writing an automation for work and am stuck with a dropdown. The particular select box in question is as follows:

<span class="a-dropdown-container" id="select-size-bulk-asin">
    <select name="display_type" class="a-native-dropdown">
        <option value="SMALL-IMAGES">SMALL-IMAGES</option>
        <option value="LARGE-IMAGES">LARGE-IMAGES</option>
        <option value="TEXT">TEXT</option>
    </select>

    <span tabindex="-1" data-a-class="a-spacing-small" class="a-button a-button-dropdown a-spacing-small">
        <span class="a-button-inner">
        <span class="a-button-text a-declarative" data-action="a-dropdown-button" aria-haspopup="true" role="button" tabindex="0" aria-pressed="false" aria-owns="2_dropdown_combobox">
        <span class="a-dropdown-prompt">SMALL-IMAGES</span>
        </span>
        <i class="a-icon a-icon-dropdown"></i>
        </span>
        </span>
    </span>

It defaults to 'SMALL Images' and I would like to select the 'TEXT' option. I am receiving element not clickable error. The page is simple and the element is visible on the screen.

The list of methods I did try are:

  • Used WebDriverWait to wait for the element to be visible;
  • Used WebDriverWait to wait for the element to be clickable;
  • Used the select class to set the selected option;
  • I also read through a question.

I am thinking if I should just go to the next element and send Shift+Tabs until I reach this drop down and then down arrow keys. But would like to use that only as the last resort.

NOTE: - I am using Python 3 and Chrome.


回答1:


You can try this code to select value from drop down :

select = Select(driver.find_element_by_id('select-size-bulk-asin'))
select.select_by_visible_text('TEXT')  

However,as you have mentioned you are receiving element not clickable exception. you can try this code :

WebDriverWait(browser, 30).until(EC.element_to_be_clickable((By.ID, "select-size-bulk-asin")))

As a last resort you can go ahead with :

drop_down= driver.find_element_by_id("select-size-bulk-asin")
drop_down.click()

actions = ActionChains(driver)
actions.send_keys(Keys.ARROW_DOWN)
actions.send_keys(Keys.ARROW_DOWN)
actions.send_keys(Keys.ENTER)
actions.perform()


来源:https://stackoverflow.com/questions/51008054/select-a-dropdown-using-python-selenium

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!