问题
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