Hi..Above is my test case.Unable to create xpath for account link.
Here is script i tried:
WebDriver Driver=new FirefoxDriver();
Driver.get("http://live.guru99.com/");
WebElement element=Driver.findElement(By.linkText("My Account"));
element.click();
It would be great if someone helps me.
Thanks in advance.
Your code is almost correct.
BUT By.linkText
works on the link text as you see it with your eyes on the website (after all CSS is applied).
If you have a look at http://live.guru99.com/ you will see that the link you are searching for is in capital letters:
"MY ACCOUNT"
But you tried to find "My Account".
So just change the third line in your code to:
WebElement element=Driver.findElement(By.linkText("MY ACCOUNT"));
And everything should work just fine!
I see people answering using the following code:
Driver.findElement(By.xpath("//a[@title='My Account']"))
This is dangerous! Why? Because there are two elements that fit this findElement query!! Check it for yourself by running the following code:
System.out.println(Driver.findElements(By.xpath("//a[@title = 'My Account']")).size());
This returns 2! (First link is directly visible as "MY ACCOUNT", the other one can be seen if you click on "ACCOUNT" then in the dropdown there is another link visible as "My Account". Both links have the same title but are different elements).
We are lucky that in this case, both elements bring you to the same desired location.
BUT in my experience this is usually not the case. On many poorly written websites you have several elements with the same title, then it is pure luck, if the element that is returned by this kind of query returns the element that you wanted.
For this reason it is always a good idea to check how many Elements there are that fit your query using "findElements".
Let's say one day this guru99 site would decide to use uppercase for both links. Then also the approach of this answer would suffer from this problem.
That's why it might be a good strategy to use another locator to narrow the search for the link down.
Analyzing the site I would go for "footer":
WebElement footer=Driver.findElement(By.className("footer"));
WebElement link=footer.findElement(By.linkText("MY ACCOUNT"));