Tuesday, February 9, 2016

WebDriver - FindElement Examples

WebDriver - FindElement Examples


In this post you will see examples of how to locate an element by Id, ClassName, Name, TagName, CssSelector, LinkText, PartialLinkText and XPath.

Google search text field is mostly used for the examples below. Open 'google.com' in FireFox. Right click on search text field and click on Inspect Element(Q).


You can see (below) the inspector that opens on clicking the Inspect Element(Q) for search text field (see above image). From this highlighted part we will use the Id, ClassName etc. needed for finding search text field in our examples.


Here we are finding the search text field using "Id" and writing text "Selenium" in it via SendKeys.


Similarly we can inspect the element for the following link (Explore tips to help you stay safe online) on 'google.com' and use the text while finding the element using LinkText and PartialLinkText.


Below inspector opens on clicking Inspect Element(Q) for the link (see above image).


Below you can see all the ways of locating elements. Most of it is self explanatory. Take a look at the code line 27, where we are using TagName. We have used "input" tag here. There were many input tags on the page, so we had to use "FindElements" instead of "FindElement" and have used fourth "input" tag. Use one of the FindElement statements at a time and run the below code. It should work fine. One more thing, in line 31 and 33 it is finding the link (using LinkText & PartialLinkText) and clicking it.

So as seen in above code you can locate an element with FindElement using Id, ClassName, Name, TagName, CssSelector, LinkText etc. and do actions on it.