środa, 1 lutego 2012

Xpath – count options in dropdown

Often we want our script to flexibly react on what’s appearing on a web page. The way to achieve that is to count how many results, rows in a table, pages etc. is present at exact moment, because numbers don’t lie…


(400 goldfishes = 1200 fulfilled wishes,
Numbers don’t lie”)


Our example includes random choice of brand and model of car on http://www.motors.ebay.com/.

We’ll use command “storeXpathCount” which counts number of xml nodes. Web page is not an xml document but xpath (XML Path Language) allows to search (make queries) through web page as it were an xml document. Here you can find more about xpaths: http://www.w3schools.com/xpath/xpath_intro.asp.



And these are our dropdowns:
























The trick is that when you choose brand then number of options in the next dropdown changes. After you record selecting brand from first dropdown the next step is to change locator:



Now change command from “select” into “storeXpathCount” and in third column (Value) type name of variable which will store the result:


If you run script at this moment, value of “brandCount” would equal 1 because it counts number of dropdowns with id “_mak_new” (and there’s only one). You should modify target like this:

//select[@id='_mak_new']/option

Now it counts number of options in this dropdown.

Below is whole script which firstly counts number of options in first dropdown, randomly chooses one of them, then counts number of options in second dropdown and again randomly chooses one of them.



easy to copy version:

open | http://www.motors.ebay.com/
storeXpathCount | //select[@id='_mak_new']/option | brandCount
store | javascript{Math.floor(storedVars['brandCount']*Math.random()+0)} | brand
select | id=_mak_new | index=${brand}
storeXpathCount | //select[@id='_mod_new']/option | modelCount
store | javascript{Math.floor(storedVars['modelCount']*Math.random()+0)} | model
select | id=_mod_new | index=${model}



As you can see in strings generating random numbers the lower boundary is “0” because in these dropdowns first elements have value “0” (not 1). Selecting e.g. 2nd element will look like:
select | id=_mod_new | index=1