-1

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?

2 Answers2

1

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

Shrini
  • 193
  • 10
0

Create a page object file.

For example, if you are using an xPath like "//div[@id='login_box']//input[@type='submit']" a lot, in the page object file put:

var loginSubmit = "//div[@id='login_box']//input[@type='submit']"

Then in your main file import the page object file:

using myPageObjectFile

driver.FindElement(By.XPath(myPageObjectFile.loginSubmit));

My C# is not great so it might not be like this exactly. But something to that effect should work.

This way when the xPath changes, you only need to adjust it in the page object file.

Alichino
  • 1,668
  • 2
  • 16
  • 25