I would like to get xPATH from hyperlink text or button from the webpage. For example, I want to get an xPATH of "Gmail" hyperlink text or "Google Search" button from https://www.google.com/ in JAVA.
Have someone guide me how to Generating xPATH using JAVA?
My attempt
public void xPathGenerator(String valueForXPath) throws IOException, ParserConfigurationException, SAXException, TransformerException {
URL url = new URL("https://www.google.com/");
DocumentBuilderFactory docBuildFac = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuild = docBuildFac.newDocumentBuilder();
Document doc = docBuild.parse(url.openStream());
System.out.println("Node name: " + doc.getDocumentElement().getNodeName());
System.out.println("xPath : " + getXPath(doc.getDocumentElement(), valueForXPath));}
private String getXPath(Node documentElement, String valueForXPath) {
for (int i = 0; i < documentElement.getChildNodes().getLength(); i++) {
Node node = documentElement.getChildNodes().item(i);
if(node instanceof Element) {
if(node.getNodeName().equalsIgnoreCase(valueForXPath)) {
return "/" + node.getNodeName();
} else if (node.getChildNodes().getLength() > 0) {
String xpath = getXPath(node, valueForXPath);
if (xpath != null) {
return "/" + node.getNodeName() + xpath;
}
}
}
}
return null;
}
Thanks