While onsite doing a workshop today we ran into a rather annoying problem when trying to move from statically choosing an item from a select box to selecting a random value from it. Or in code…

<pre lang="python">self.se.select('title', 'Mr')

to

<pre lang="python">locators{"title_select": "css=#title"}

how_many = self.se.get_css_count("%s option" % locators["title_select"])
which_one = random.randint(1, how_many)
self.se.select(locators["title_select"], "index=%d" % which_one)

The problem surfaced immediately with the script blowing up saying that the how_many was 0. What?!?! The other static scripts were working properly so its not as if the locator was hosed.

A little digging and some Google-fu turned up a suggestion that get_css_count and get_xpath_count have a bit of a hitch when being run against pages that use frames. As this one did (actually, it was a frame in a frame in a frame). So to make the script calculate the count correctly, specifically putting in the frame context was necessary resulting in this working blob of code.

<pre lang="python">locators{"title_select": "css=#title"}

self.se.set_frame("name=my_frame")
how_many = self.se.get_css_count("%s option" % locators["title_select"])
which_one = random.randint(1, how_many)
self.se.select(locators["title_select"], "index=%d" % which_one)

And with that they removed some hard-coded script data and instead lets the application provide the choices to choose from.