a programmers ramblings about everything

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:

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

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)”

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…

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.