2
\$\begingroup\$

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

Select(self.driver.find_element_by_id("currencyid")).select_by_visible_text("AUD")
Select(self.driver.find_element_by_id("excur")).select_by_visible_text("AUD")

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?

\$\endgroup\$

migrated from stackoverflow.com Jan 17 '17 at 15:00

This question came from our site for professional and enthusiast programmers.

7
\$\begingroup\$

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"))

currency.select_by_visible_text("AUD")
excur.select_by_visible_text("AUD")

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))
    select.select_by_visible_text(value)

    assert select.first_selected_option.text == value
\$\endgroup\$

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.