Selenium, Firebug and Xpath (updated)

Posted: February 2nd, 2011 | Author: | Filed under: general | 2 Comments »

Today I was working on writing a selenium test to ensure a feature was working properly on our site.  The button I was trying to click had a duplicate button on the page and each did something different.  The problem was that they were both in different forms, but had the same name and no ID.  In  selenium the only way to target the specific button is via XPath.  The XPath for this is a little crazy:

//div/div[2]/div/div/div[2]/div/div/div[2]/div[2]/div[2]/div[2]/div/form/input[13]

Now I spent a bit of time trying to figure it out manually and quickly gave up.  I figured firebug might have something and sure enough if you “Inspect Element” on the button firebug pops up with the full html path to the element shown across the top of the firebug window.  Hovering over each element gives you the full XPath and right clicking lets you do a few different operations such as Copy Html and Copy XPath.  Now the XPath that it gives you will look like

/html/body/div/div[2]/div/div/div[2]/div/div/div/div[2]/div[2]/div[2]/div/form/input[13]

I removed the /html/body and replaced with // to match the rest of the XPath that selenium generates, replaced the name=fieldname in my test and it worked.

*Please NOTE*

This is horrible don’t ever use it 🙂 – All joking aside if you have the option to add a class or an id(as rasenplanscher points out in the comments below) to an element on the page that you need to target you should do that instead.  If you can’t like this situation, this will work for you.


2 Comments on “Selenium, Firebug and Xpath (updated)”

  1. 1 rasenplanscher said at 3:13 pm on February 22nd, 2011:

    Not cool, dude!

    Your nesting, that is. I have never seen any page that needs or even warrants that depth of nesting. Three or four levels inside the body are usually enough, one or two more for very complex designs — but that’s about it.

    Also, you shouldn’t need the whole path — use classes. That kind of hardwiring makes your tests rather brittle — just add a new box somewhere and [BAM] everything goes red for no apparent reason and you waste precious minutes on determining the cause and updating the paths, possibly in a lot of places…

  2. 2 David Herman said at 4:09 pm on February 22nd, 2011:

    I completely agree with you and I should edit to reflect this however for the purpose of this I did not have the option to make any changes. This is testing a design that has been around for a few years and with limited resources it wasn’t going to change any time soon. Using a class OR id would be the best option but when you don’t have ability to make changes to the underlying html.