I have written the following code for the selenium Python select function and the code works fine.


select1 = Select(self.driver.find_element_by_id("currencyid")).first_selected_option.text
select2 = Select(self.driver.find_element_by_id("excur")).first_selected_option.text
assert select1 == "USD"
assert select2 == "CAD"

Is there anything I can do this to reduce the steps and to make it cleaner? Do I need to define the ids twice?


You don't have to recreate the Select instances, define once and reuse:

currency = Select(self.driver.find_element_by_id("currencyid"))
excur = Select(self.driver.find_element_by_id("excur"))


assert currency.first_selected_option.text == "USD"  # should not be "AUD"?
assert excur.first_selected_option.text == "CAD"  # should not be "AUD"?

If you have more select elements, this approach would not scale well, you can further improve the code and put the logic into a loop, something like:

values = [("currencyid", "AUD"), ("excur", "AUD")]
for id, value in values:
    select = Select(self.driver.find_element_by_id(id))

    assert select.first_selected_option.text == value
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.