How to find a web element using FindElement Method?
June 11, 2022
How to find a web element using FindElement Method
Welcome to this post!-“How to find a web element using FindElement Method?”
If you are looking for latest Selenium Webdriver concepts related tointerview questions, then you are at right place. This post – “Selenium: How to find a web element using FindElement Method?” consists of discussion on FindElement method and a Complete Example.
Plus this post will give a broader perspective on the usage and implementation of FindElement using java in Selenium.
Usually these are assumed to be known in depth to check the logical solvency efficiency of the candidate and of course, suitability for the project and company. Go ahead and enjoy reading…
This discussion will help you prepare well if you are going for the interview or you need the function to be used in your project.
In the interview usually, you might be questioned in different ways like:
- How to identify an element using selenium?
- How can you locate an element on web application using selenium?
- How to index an element on web page using selenium?
- Can you use classname to identify an element in selenium? If yes then how.
And so on.
In this post, I will discuss the findElement method which is being used for identifying the elements on UI or web page, then I will show you some examples on various identification methods\ways of identifying same UI element post which we will see final complete example.
How To Find Or Locate Objects On Webpage?
Before we start our discussion on Selenium’s various available options, let’s first try to analyze the page and elements to understand how these are structured in the application, what properties or attributes are defined for the web elements, and so on.
Every Browser renders visual elements of the web application for users by hiding the HTML code and its related resources. If we want to automate some page or pages of web application using Selenium then one must be able to understand the html code. As in html every element has a tag. This tag is used for web element locator.
To view a page source, right click in browser window and you will see lot of options. Then select “ View Page Source” option from the pop-up menu. This will display the HTML code of the page in a separate window.
Inspecting pages and elements with Firefox and Xpath add-on
The newer versions of Firefox provide in-built ways to analyze the page and elements. And which is why they have new option for you either you keep on updating Firefox and work with newest version. Second is that you download Firefox developer edition for your debugging, etc purposes.
Note: So ideally your normal Firefox is enough for inspecting and to take a walkthrough down the DOM.
You only need to install the XPath Finder add-on in Firefox from https://github.com/trembacz/xpath-finder .
Following is the usage of this tool, follow below steps:
Let’s take an example of Google Home Page.
Step 1–> Click on the plug-in icon, cursor will be changed to the crosshair.
Step 2–> Hover over the desired element (elements are highlighted on hover).
Step 3–> Click on the element and his xPath will display in the panel at the bottom of the page.
Let’s understand each of the main topics one by one and with examples.
Understanding FindElement Method
The findElement() method returns a WebElement object based on a specified search criteria. The search criteria for this method is a locator (a tag, a class, etc) or query object which is passed as an instance of “By” class to be passed as single main argument.
What if you end up in error?
This method throws an exception if it does not find any element matching the search criteria.
The following table lists various locators supported by Selenium WebDriver:
Name | Syntax in JAVA | Description |
By ID | driver.findElement(By.id(<element ID>)) | Locates an element the using the ID property |
By name | driver.findElement(By. name(<element name>)) | Locates an element using the Name property |
By class name | driver.findElement(By. className(<element class>)) | Locates an element using the Class property |
By TagName | driver.findElement(By.tagName(<html tag name>)) | Locates an element using the HTML tag |
By linkText | driver.findElement(By.linkText(<link text>)) | Locates link using it’s text |
By partial linktext | driver.findElement(By.partialLinkText(<link text>)) | Locates link using it’s partial text |
By CSS | driver.findElement(By.cssSelector(<css selector>)) | Locates element using the CSS selector |
By XPath | driver.findElement(By.xpath(<xpath query expression>)) | Locates element using XPath query |
NOTE
The most preferred way of locating elements on UI are using id, name, or class attributes.
Let’s try using these methods to locate elements as described in the following sections.
Finding element by the ID property
The ID property is the most preferred way to locate elements on a page and this always identifies the control uniquely.
The only problem lies with this is when you have more non-unique id’s or developer has set the code to be auto-generated id’s.
Let’s say we have a form on the web page, for login, as below:
<form name="login_Form1"> <label for="username">UserName: </label> <input type="text"id="username" class=”class1”/> <br/> <label for="password">Password: </label> <inputtype="password" class=”class2” id="password" /> <br/> <input name="login" type="submit" class=”class3” value="Login" /> </form>
Then we can follow with the code as
>WebElement usernameEle = driver.findElement(By.Id(“username”)); WebElement passwordEle = driver.findElement(By.Id(“password”)); WebElement SubmitEle = driver.findElement(By.Id(“Login”));
Finding element by the Name property
The Name property is the 2nd most preferred way to locate elements on a page.
The Name property also identifies the control uniquely and is very reliable. The only problem comes into picture when more than one control has same name.
Let’s say we have a form on the web page, for login, as below:
<form name="login_Form1"> <label name="username">UserName: </label> <input type="text"id="username"class=”class1”/> <br/> <label name="password">Password: </label> <inputtype="password" class=”class2” id="password" /> <br/> <input name="login" type="submit"class=”class3” value="Login" /> </form>
Then we can follow with the code as
WebElement usernameEle = driver.findElement(By.Name(“username”)); WebElement passwordEle = driver.findElement(By.Name(“password”)); WebElement SubmitEle = driver.findElement(By.Name(“Login”));
Try Yourself:
Identify elements using class name.
Finding element by the ClassName property
The ClassName property is another preferred way to locate elements on a page incase above two doesn’t work.
Usually the class names are unique as per controls. And hence to identify them is much easier.
This also has same problem like ID if non-unique then method fails.
Let’s say we have a form on the web page, for login, as below:
<form name="login_Form1"> <label name="username">UserName: </label> <input type="text"id="username"class=”class1”/> <br/> <label name="password">Password: </label> <inputtype="password" class=”class2” id="password" /> <br/> <input name="login" type="submit"class=”class3” value="Login" /> </form>
Then we can follow with the code as
WebElement usernameEle = driver.findElement(By.ClassName(“class1”)); WebElement passwordEle = driver.findElement(By.Name(“class2”)); WebElement SubmitEle = driver.findElement(By.Name(“class3”));
Finding element by the Tag Name property
The Tag Name property is another preferred way to locate elements on a frames of the web-page.
Let’s say we have a form on the web page, for login, as below:
<iframe src="..."></iframe>
Then we can follow with the code as
WebElement frameEle = driver.findElement(By.tagName("iframe"));
Finding element by the Link Text property
The most easiest way of recognizing the links on any web page is by finding the visible text. In this method you only need to pass elements matching visible text.
Let’s say we have a form on the web page, for login, as below:
<a href="http://www.google.com/search?q=quick">quick</a>>
Then we can follow with the code as
WebElement quickEle= driver.findElement(By.linkText("quick"));
Finding element by the Partial Link Text property
The other most easiest way of recognizing the links on any web page is by finding the visible partial text. In this method you only need to pass elements matching close to or partial visible text.
Let’s say we have a form on the web page, for login, as below:
<a href="http://www.google.com/search?q=quick">search for quick</a>>
Then we can follow with the code as
WebElement quickEle= driver.findElement(By.partialLinkText("quick"));
Finding element by the CSS property
Like the name implies it is a locator strategy by css.
Note:
1. Native browser support is used by default, so please refer to w3c css selectors for a list of generally available css selectors.
2. Beware that not all browsers were created equal, some css that might work in one version may not work in another.
Let’s say we have a div on the web page, for login, as below:
<div id="food"><span class="dairy">milk</span><span class="dairy aged">cheddar cheese</span></div>
Then we can follow with the code as
WebElement cheese = driver.findElement(By.cssSelector("#food span.dairy.aged"));
Finding element by the XPath property
Like the name implies it is a locator strategy by Xpath.
Let’s say we have a input search box on the google home page, for login, as below:
<input class="gLFyf gsfi" maxlength="2048" name="q" type="text" jsaction="paste:puy29d" aria-autocomplete="both" aria-haspopup="false" autocapitalize="off" autocomplete="off" autocorrect="off" role="combobox" spellcheck="false" title="Search" value="" aria-label="Search">
Then we can follow with the code as
WebElement seachboxEle = driver.findElement(By.xpath("/html/body/div[1]/div[3]/form/div[2]/div/div[1]/div/div[1]/input"));
Finding Child element
The WebElement class supports “find methods” such that it helps in finding descendant or child elements.
For example, suppose that there are some duplicate web elements on a page and they are located in separate “<div>” web elements. In order to locate such element we need to find the parent <div> element and then locate the descendant or child element within the context of the parent “<div>” element in the following way:
Step 1:
WebElement divWebEle = driver.findElement(By.id("div1"));
Step 2:
WebElement bottomLinkWebEle = divWebEle.findElement(By.linkText("bottom"));
Or a Shortcut can be used:
WebElement bottomLinkWebEle = driver.findElement(By.id("div1")).findElement(By.linkText("bottom"));
Conclusion:
Selenium WebDriver interface provides the findElement() method which traverse through the specified criteria and locates the web elements in the DOM for matching web elements of same type, and finally returns the “first” matching element. SO let’s quickly recap all the locator methods:
By.ID
By.Name
By.ClassName
By.TagName
By.LinkText
By.PartialLinktext
By.CSS
By.XPath
This brings us to the end of our discussion on “How to find a web element using FindElement Method?”. Now we will see how we can find elements using findelements method? and how is it different from FindElement method.
I really hope you have enjoyed reading the post. If you have any doubt on this please feel free to add your comment below.
If you would like to keep track of further articles on Selenium. I recommend you to SUBSCRIBE by Email and have new Selenium articles sent directly to your inbox.