Search code examples
htmlseleniumscreen-scrapingautomated-tests

Selenium: Not able to understand xPath


I have some HTML like this:

<h4 class="box_header clearfix">
<span>
<a rel="dialog" href="http://www.google.com/?q=word">Search</a>
</span>
<small>
<span>
<a rel="dialog" href="http://www.google.com/?q=word">Search</a>
</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?


Solution

  • 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");