Search code examples
c#seleniumxpathreadable

Make selenium code with a lot of XPath-s more readable


I've noticed that when I'm using selenium web driver to interact with elements on a web page my code becomes not readable because I use a lot of XPath-s to find this elements. For example:

driver.FindElement(By.XPath("//div[@class='login']//a[@href='#']"), Globals.TIMEOUT).Click();
var loginField = driver.FindElement(By.XPath("//div[@id='login_box']//input[@name='login_name']"));
jdriver.ExecuteScript("arguments[0].setAttribute('value', '" + login + "')", loginField);
var passwordField = driver.FindElement(By.XPath("//div[@id='login_box']//input[@name='login_password']"));
jdriver.ExecuteScript("arguments[0].setAttribute('value', '" + password + "')", passwordField);
driver.FindElement(By.XPath("//div[@id='login_box']//input[@type='submit']")).Click();
driver.FindElement(By.XPath("//div[@class='nameuser']"), Globals.TIMEOUT);
I thought that I can place XPath values into constant strings but it's very helpful to see the actual XPath of the element while reading the code. But on the other hand, when the XPath of some object changes I have to change it at all places it is used. So what is the best solution for this problem?

Solution

  • Use Selenium Page Object Model using Page factory. Helps to maintain clean code and enhances readability of code.