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?

200_success
145k22 gold badges190 silver badges478 bronze badges
asked Jan 17, 2017 at 14:41
\$\endgroup\$
0

1 Answer 1

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
answered Jan 17, 2017 at 14:48
\$\endgroup\$
0

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.