Selenium Python Select the first item from a drop down by index is not working. Unbound method select_by_index

不羁的心 提交于 2020-07-08 12:53:44

问题


I am trying to click the first item from a drop down. I want to use it's index value because the value could be different each time. I only need to select the 1st item in the drop down for this particular test. I have tried Select.select_by_index(1)

I am getting the error:

    Traceback (most recent call last):
  File "C:\Webdriver\ClearCore 501 Regression Test\ClearCore - Regression Test\TestCases\DataPreviewsPage_TestCase.py", line 398, in test_a2_sort_data_preview_advanced
    data_previews_view_page.select_option_from_new_sort_drop_down() # Select the sort from the sort drop down to view the sorted fields
  File "C:\Webdriver\ClearCore 501 Regression Test\ClearCore - Regression Test\Pages\data_previews_view.py", line 144, in select_option_from_new_sort_drop_down
    Select.select_by_index(1) # select the 1st item from the sort drop down
TypeError: unbound method select_by_index() must be called with Select instance as first argument (got int instance instead)

My code snippet to call the drop down is:

def select_option_from_new_sort_drop_down(self): # When sort is ready, select the 1st value from the drop to run the sort
    select = Select(WebDriverWait(self.driver, 20).until(EC.element_to_be_clickable((By.XPATH, '//option[contains(., "(A-Z)")]'))))
    Select.select_by_index(1) # select the 1st item from the sort drop down

I am using Selenium in Python

Thanks, Riaz


回答1:


I think you need to use select instead of Select on selecting by index like below (and also i hope need to use 0 for first option in java prospective)

select.select_by_index(1) # select the 1st item from the sort drop down

In Java generally i will use like this

  Select oSelect = new Select(driver.findElement(By.id("myDropdown")));
  oSelect.selectByIndex(0);

Thank You, Murali




回答2:


For python use:

from selenium.webdriver.support.select import Select
my_select = Select( driver.find_element_by_id("some_id") )
my_select.select_by_index(1)


来源:https://stackoverflow.com/questions/35413232/selenium-python-select-the-first-item-from-a-drop-down-by-index-is-not-working

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