Sunday, March 27, 2011

Using Firebug to help solve xpath issues for Selenium 2.0

Of course, we should be avoiding xpath where we can, but here is what I have learned about Firebug while trying to click on tricky button is Selenium.
Firebug is a very useful tool when using Selenium 2.0 to click on elements on the page. We can use the similar example as we used in the previous post for Etsy.com, where we found the element of the "Sell" link and used xpath to click on it in Selenium 2.0.

Before we explore the world of Firebug and locating elements. What is an element?
Here is a great example from w3Schools.
Firebug on FireFox is yet another add-on that can easily be installed by going to Tool > Add-ons. Once you have installed it and restarted your browser you will see the Firebug icon on the bottom left corner. Click it.

Firefox will be split in two one will be the site that we are on (Etsy) and the other will be Firebug. We will get the element for the "Sell" link.

To do this click on the Element inspect icon on the top left corner of the Firebug window.
Then point and click on the "Sell" link on the Etsy website, and we will get this:
What does this mean to us? There is an id for an element which is the header of the page, under that header is a title which has a link "Sell on Etsy".

To click on this link using Selenium 2.0 + Groovy we will say:
findElement(By.xpath("//a[@title='Sell on Etsy']").click()
this will take us to the Sell page.

That is an example of using Firebug to find the element and then using Xpath to click on the element, how about we find an element that does not necessarily require us to use xpath?

When we want to click the search button on Etsy.com after we enter whatever that is we are looking for. Let us look for the element id for the search button so get out your Firebug and chose the inspect tool and click the search button, we will get this:
In this case we have an id for the element which lets us just go through and write our script without having to use Xpath. This is what we will say using Selenium 2.0 + Groovy:
findElement(By.id("search_submit").click() - findElement(By.xpath("//button[@id='search_submit']").click()
both of these will click the button but the first example is shorter and better since it goes right to the element using its ID - "search_submit" bypassing xpath which may change over time.





No comments:

Post a Comment