0

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

  • Share your attempt... To learn xpath: http://www.w3schools.com/xsl/xpath_syntax.asp https://www.w3.org/TR/xpath/ – Sid Oct 12 '16 at 21:46
  • I doubt this is feasable in the genral case. XPath works on well formed XML. HTML pages are not valid XML generally speaking. https://stackoverflow.com/questions/5558502/is-html5-valid-xml Parsing web pages using a XML Bulder is bound to fail at some point, unless you are sure of the pages you try to parse. – GPI Jul 05 '17 at 12:03

1 Answers1

0

Try this code to search in google chrome, it worked for me.

System.setProperty("webdriver.chrome.driver", "D://Driver//chromedriver.exe");
WebDriver drchrome = new ChromeDriver();
drchrome.get("https://www.google.com");
WebElement find = drchrome.findElement(By.id("lst-ib")); 
find.sendKeys(new String[] {"arsenal"});
find.submit();
buræquete
  • 14,226
  • 4
  • 44
  • 89