Is xpath different for different browser?

OPTIMUS picture OPTIMUS · Apr 14, 2014 · Viewed 10.8k times · Source

I am having a very funny issue. I am having a xpath through which i am retrieving value.

Ex.

System.out.print(driver.findElement(By.xpath("//*[@id='error-box']/ul/li")).getText().toString());

In firefox and Chrome it is giving same text while in IE it is giving different text.

Is there any difference between xpath of various browser or it is some other issue which i am not getting.

Answer

Andrejs picture Andrejs · Feb 20, 2016

Read up on how Selenium handles Xpaths here.

In Chrome and Firefox, I right-clicked on the same DOM element (as described here), selected "copy Xpath" and this is what I got:

Chrome: //*[@id="js-pjax-container"]/div2/div2/form/button

Firefox (with Firebug): /html/body/div[4]/div2/div2/div2/form/button

(one is with attribute value and the other (FF) is the absolute path, which demonstrates that FF doesn't understand Crhome generated Xpath)

So for Selenium test purposes, it matters between browsers. (I didn't test on IE)

I ran this

 @Test
        public void testGitHubButton(){
        WebDriver driver = new FirefoxDriver();
        driver.get("https://github.com/");
       String signup = driver.findElement(By.xpath("/html/body/div[4]/div[1]/div[1]/div[1]/form/button")).getText();
           Assert.assertEquals("Testing for string equality", "Sign up for GitHub", signup );
        driver.close();
        driver.quit();
        }

And the test passes. If I copy paste Chrome's Xpath in there, it will fail.