views:

814

answers:

2

I have some HTML like this:

<h4 class="box_header clearfix">
<span>
<a rel="dialog" href="http://www.google.com/?q=word"&gt;Search&lt;/a&gt;
</span>
<small>
<span>
<a rel="dialog" href="http://www.google.com/?q=word"&gt;Search&lt;/a&gt;
</span>
</h4>

I am trying to get the href here in Java using Selenium. I have tried the following:

selenium.getText("xpath=/descendant::h4[@class='box_header clearfix']/");
selenium.getAttribute("xpath=/descendant::h4[@class='box_header clearfix']/");

But none of these work. It keeps complaining that my xpath is invalid. Can someone tell me what mistake I am doing?

+1  A: 

I had similar problems with Selenium and xpath in the past and couldn't really resolve it (other than changing the expression). Just to be sure I suggest trying your xpath expressions with the XPath Checker addon for firefox.

Igor Brejc
Thanks. I will install that and check it Just to make sure I am on the right path, am I using XPath correctly with selenium? I mean which one should I use: getText or getAttribute?
Legend
+3  A: 

You should use getAttribute to get the href of the link. Your XPath needs a reference to the final node, plus the required attribute. The following should work:

selenium.getAttribute("xpath=/descendant::h4[@class='box_header clearfix']/a@href");

You could also modify your XPath so that it's a bit more flexible to change, or even use CSS to locate the element:

//modified xpath
selenium.getAttribute("//h4[contains(@class,'box_header')]/a@href");

//css locator
selenium.getAttribute("css=.box_header a@href");
Dave Hunt
Igor Brejc
@Igor It's a balance of allowing your application to change somewhat without your tests failing, and your tests running faster. I generally prefer not to fix tests between application changes so don't mind the XPath taking a little bit longer. Of course you could also use CSS locators, which are faster and (generally) more flexible. :)
Dave Hunt
Thank You for the advice. This was just a testing for the testing app so I will keep that in mind. The ids and classnames are almost dynamically being generated so I was left with just XPath in the end...
Legend