I am trying to get the XPath and CSS path of an element using Java. I have used jsoup to parse the HTML and I am getting the CSS path, but in some cases it is returning the wrong path. (I am matching it with Selenium generated paths.)
I am using this code to generate CSS path my element is "s-Rectangle_44"
<div id="s-Rectangle_44" class="rectangle firer click commentable">
<div class="clipping">
<div class="content">
<div class="valign">
<span id="rtr-s-Rectangle_44_0"></span>
</div>
</div>
</div>
</div>
And selenium is giving css path as css=#s-Rectangle_44 > div.clipping > div.content > div.valign while I am getting array Index out of bound exception.I need to get the XPath also. Is there any other method to get this? Can I use Firebug with Java?
public static String getCssPath(Element el) {
if (el == null)
return "";
if (!el.id().isEmpty())
return "#" + el.id();
StringBuilder selector = new StringBuilder(el.tagName());
String classes = StringUtil.join(el.classNames(), ".");
if (!classes.isEmpty())
selector.append('.').append(classes);
if (el.parent() == null)
return selector.toString();
selector.insert(0, " > ");
if (el.parent().select(selector.toString()).size() > 1) {
selector.append(String.format(":nth-child(%d)",
el.elementSiblingIndex() + 1));
}
return getCssPath(el.parent()) + selector.toString();
}