Search code examples
javahtmlselenium-webdriverxpathformat

Is there any correct format for Xpath search?


So I have been in QA Test automation recently using Selenium. When I select/write the Xpath for an element, it seems that there are different format meaning that it can be done in different ways. For example


protected final String LOGIN_BUTTON_LOCATOR = "//i[contains(@class,'sign-in')]";

and

protected final String ERROR_MESSAGE_LOCATOR = "//div[@class='flash error' and @id='flash']";

As you see above, the class name is written in a different format. Both work for me now, but is there any way that is preferred more over another?


Solution

  • It might be that "find all the students called 'Jim'" and "find all the students who got an 'A' grade" have the same answer, but they are completely different questions, and asking which of the two questions is "correct" or "preferred" is meaningless. You have given us two completely different XPath expressions and asked which is better - we can only say the one that is better is the one that correctly reflects your intent.

    Note that @class="x" tests whether the value of the class attribute is exactly equal to "x", whereas contains(@class, 'x') tests whether it contains "x" as a substring. Using contains where you meant = is a common mistake, but it's not wrong if matching a substring is what you intended.