\$\begingroup\$
\$\endgroup\$
0
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
1 Answer 1
\$\begingroup\$
\$\endgroup\$
0
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
lang-py