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&l开发者_运维百科t;/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?
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");
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.
精彩评论