We are aware that a webpage consists of numerous WebElements such as text boxes, buttons, lists, etc. We can perform a diversity of actions on these WebElements using Selenium commands like search elements, associate events with web elements, etc. To perform these deportment we showtime need to interact with a web page so that we tin apply WebElement Commands/deportment. In this topic, we will hash out the dissimilar methods used to find an element on the webpage using Selenium and so that nosotros tin perform actions on these elements. We will cover the following topics in this commodity.

  • Discover elements using Selenium WebDriver?
  • Why do we demand to find a spider web chemical element in Selenium?
  • How to detect elements in Selenium?
  • What is Past class in Selenium?
  • Difference betwixt find Element and find Elements in Selenium.

Find elements using Selenium WebDriver?

Equally mentioned above to interact with WebElements, we first have to notice or locate these elements on the webpage. Nosotros can find elements on a spider web folio past specifying the attributes such as Id of the element or grade name of the element and such other parameters. These alternatives using which we tin find elements on a webpage are called locator strategies.

The post-obit are the locator strategies nosotros can utilize while locating the elements.

Locator Clarification
id finds elements by ID attribute. The search value given should match the ID attribute.
name Finds or Locates elements based on the Proper noun attribute. The proper name attribute is used to lucifer the search value.
class proper name Finds elements that match the class name specified. Annotation that compound classes are not allowed equally strategy names.
tag name Finds or Locates elements having tag names that match the search value.
CSS selector Matches CSS selector to find the element.
XPath Matches XPath expression to the search value and based on that the chemical element is located.
link text Here the visible text whose anchor elements are to exist found is matched with the search value.
partial link text Here also we lucifer the visible text with the search value and find the ballast value. If we are matching multiple elements, but the first entry will be selected.

Now before moving to how nosotros tin use these diverse types of locators to locate the elements, let's offset sympathize why exactly at that place is a need to find the elements in Selenium?

Why practice we need to detect an element in Selenium?

We know that we useSelenium mostly for UI testing of a spider web-based application. Since we need to perform automated feature interaction with the spider web page, we demand to locate web elements then that we can trigger some JavaScript events on web elements similar click, select, enter, etc. or add together/ update values in the text fields. To perform these activities it is important to outset locate the element on the web page and and then perform all these actions.

For example, suppose given a web page "demoqa.com" as shown below.

demoqa.com example website

Now, allow usa say we need to perform some actions on the "JOIN NOW " button. And so before implementing the code for the say click upshot on this button, nosotros will have to first find this chemical element on the spider web folio. So, how we are going to discover the element so that we tin conduct on with our actions?

We will utilize two methods 'findElement' and 'findElements' provided past Selenium WebDriver for this purpose. Now let the states get alee and understand the details of these methods.

How to notice elements in Selenium?

As discussed, Selenium WebDriver provides two methods using which we tin find an element or list of elements on a web page. These are:

findElement(): This method uniquely finds a web element on the web page.

findElements(): This method finds a list of web elements on the spider web page.

Let's understand the usage and details of these methods in the post-obit sections:

findElement() in Selenium

The findElement() method of the Selenium WebDriver finds a unique web element inside the webpage.

It'southward syntax looks like below:

          WebElement elementName = driver.findElement                   (By.LocatorStrategy("LocatorValue"));                  

Every bit shown in the in a higher place syntax, this command accepts the "Past " object equally the argument and returns a WebElement object.

The "By" is a locator or query object and accepts the locator specifier or strategies nosotros discussed above. And then if we write the line "commuter.findElement( Past.)" then the Eclipse IntelliSense will give the following locator strategies that we can acquaintance with By object.

By class members

The above screenshot shows all the options that we get when we write 'Past'. We will explicate each of these strategies in the later sections of this affiliate.

Note: In case in that location is no matching element plant, the findElement command throws NoSuchElementException.

But what happens if there are multiple elements matching the criteria provided in the findElement() method? When such a instance occurs, the findElement() method returns the first most element inside the spider web page .

findElements() in Selenium

The command findElements() returns a list of spider web elements that match the specified criteria, unlike findElement() which returned a unique element. If at that place are no matching elements then an empty list returns.

The general syntax of findElements() command in Selenium WebDriver is as below:

          List<WebElement> elementName = driver.findElements(By.LocatorStrategy("LocatorValue"));                  

Similar the findElement() command, this method too accepts the "By " object every bit the parameter and returns a WebElement   list.

Let u.s. consider an example wherein we need to find the number of elements having tag proper name as "input " on the DemoQA text box folio. The inspect panel for this is as below.

demoqa.com to find elements

In the in a higher place screenshot, when we search for the tag name 'input' two entries return (shown by the reddish rectangle around the search tool which says 1/ii).

The post-obit program shows the example of the findElements() method in which we provide the Past object with tagName.

                      import            java.util.List;            import            org.openqa.selenium.By;            import            org.openqa.selenium.WebDriver;            import            org.openqa.selenium.WebElement;            import            org.openqa.selenium.chrome.ChromeDriver;            public                          class              FindElementByTagName            {                          public              static              void              primary              (Cord[] args)            { 	   System.setProperty("webdriver.chrome.driver",            "C:/testSelenium/chromedriver.exe");		  	   WebDriver driver =            new            ChromeDriver();  	   driver.get("https://demoqa.com/text-box/");            // Find elements using tag name            List<WebElement> allInputElements = driver.findElements(By.tagName("input"));            if(allInputElements.size() !=            0)  	   { 		   System.out.println(allInputElements.size() +            " Elements establish past TagName every bit input \north");            for(WebElement inputElement : allInputElements)  		   { 			   Arrangement.out.println(inputElement.getAttribute("placeholder")); 		   } 	   }    } }                  

Following is the program output.

findElements program output

Next, let us understand how to utilize different locator strategies with findElement() and findElements() commands.

What is By class in Selenium?

In this section, we will empathise how to utilize Selenium WebDriver's findElement() and findElements() with different strategies using the Past class. The 'Past' class accepts diverse locator strategies explained higher up to observe an element or elements on a web page. Let us talk over all the By class locator strategies.

How to discover an element using the attribute "id" in Selenium?

Using "id " to observe an element is by far the most common strategy used to notice an element. Suppose if the webpage uses dynamically generated ids, then this strategy returns the start web element that matches the id.

This strategy is preferred as almost spider web pages are designed by associating ids with the elements. This is because using IDs is the easiest and quickest way to locate elements because of its simplicity while coding a web folio. The value of the id attribute is a Cord blazon parameter.

The general syntax of findElement() command using Past id strategy is :

          WebElement elm = driver.findElement(By.id("Element_Id"));                  

Equally an case consider the post-obit chemical element in the DemoQA text box page:

find an element in Selenium by Id

Here we accept selected the "submit " button (marked 1). The element code for this is marked 2 in the to a higher place screenshot.

The findElement() command corresponding to the to a higher place element:

          WebElement chemical element = driver.findElement(By.id("submit"));            // Action tin be performed on Button element            element.submit();                  

Note: If none of the web elements within the spider web folio matches the id attribute then a "NoSuchElementException" is raised.

Note:  UI developers have to ensure that the ids on the page are unique. Motorcar-generated or dynamically generated ids are commonly non-unique.

The complete programme to find an element using the "By.id " object is as seen below:

                      import            org.openqa.selenium.By;            import            org.openqa.selenium.WebDriver;            import            org.openqa.selenium.WebElement;            import            org.openqa.selenium.chrome.ChromeDriver;            public                          class              FindElementById            {                          public              static              void              chief              (Cord[] args)            { 		 	System.setProperty("webdriver.chrome.driver",            "C:/testSelenium/chromedriver.exe");		 		 	WebDriver driver =            new            ChromeDriver(); 		 	driver.get("https://demoqa.com/text-box/");         WebElement element = commuter.findElement(By.id("submit"));            if(element !=            null) { 	    Organization.out.println("Element found by ID"); 	}    } }                  

This plan gives the post-obit output.

Program Output By Id

The above program is a program to find an element using the id (By.Id) of that element. Nosotros provide an advisable URL from which we demand to search an element and then call "findElement() " with the argument By.id("elementID"). This phone call returns the given element with the specified id.

How to observe an element using the aspect "name" in Selenium?

This strategy is the same as id except that the locator locates an element using the "name" instead of "id ".

The value of the Proper name attribute accepted is of type String. The general syntax of the findElement() method with By Name strategy is as below.

          WebElement elm = driver.findElement(By.name("Element_NAME"));                  

For instance, consider the following element on the page DemoQAAutomationPracticeForm :

find an element in Selenium by Name

In the above screenshot, nosotros select the first gender value (marked 1). Its corresponding chemical element in the DOM  is highlighted (marked 2).

The respective findElement() method call for the above element is:

          WebElement element = driver.findElement(By.name("gender"));            // Action can be performed on Input Text element            element.sendKeys("ToolsQA");                  

As a consequence of this method call, the first element matching the given name attribute value returns. If we tin can not find the friction match, NoSuchElementException  raises.

Providing name as a strategy is also an efficient fashion to find an element simply again if the names are not unique then the method suffers.

For example, consider the following chemical element:

find an element in Selenium by Name more than one entries

In the higher up screenshot, there are two elements with the aforementioned proper name =  gender. In this case, the findElement() method returns the starting time element.

Following code shows the program to find an chemical element using Name (By.proper noun):

                      import            org.openqa.selenium.By;            import            org.openqa.selenium.WebDriver;            import            org.openqa.selenium.WebElement;            import            org.openqa.selenium.chrome.ChromeDriver;            public                          class              FindElementByName            {                          public              static              void              main              (String[] args)            { 	   System.setProperty("webdriver.chrome.driver",            "C:/testSelenium/chromedriver.exe");		       	   WebDriver driver =            new            ChromeDriver();  	   driver.go("https://demoqa.com/automation-do-course"); 		 	   WebElement element = driver.findElement (By.proper noun("gender"));            if(element !=            null) { 	 	System.out.println("Element found past Name"); 	   } 	} }                  

The program gives the following output.

Program Output By name

The in a higher place programme finds an chemical element in Selenium using the name. We provide the proper noun of the element that nosotros can take to search as an argument to the Past object in the 'findElement()' call.

How to detect an element using the aspect "class proper name" in Selenium?

Here the value of the "class" aspect is passed equally the locator. This strategy is by and large used to find multiple elements that utilise similar CSS classes.

The locator strategy 'Past Class Name' finds the elements on the web page based on the Course attribute value. The strategy accepts a parameter of type String. The general syntax with the Class name strategy is given by:

          List<WebElement> webList = commuter.findElements(By.className(<Element_CLASSNAME>)) ;                  

or

          WebElement elm = driver.findElement(By.className(<Element_CLASSNAME>)) ;                  

The first syntax is to obtain a list of matching elements based on Form Name while the 2d syntax is to become only one matching chemical element.

In case the chemical element has many classes, and then this strategy will friction match each of the classes.

Consider the post-obit element (submit button) on DemoQAAutomationPracticeForm :

find an element in Selenium by className

The respective command for finding the chemical element marked above is:

          WebElement parentElement = commuter.findElement(By.className("button")); parentElement.submit();                  

Annotation: Finding elements using class proper noun strategy is helpful when nosotros finish upward with non-unique IDs and names. That fourth dimension we just become for the Class Name strategy and effort to find the elements. When we use the Class Name strategy, once Selenium finds the particular grade, it then looks for ID in the specified grade.

The program to detect an element using By.className is every bit below:

                      import            org.openqa.selenium.By;            import            org.openqa.selenium.WebDriver;            import            org.openqa.selenium.WebElement;            import            org.openqa.selenium.chrome.ChromeDriver;            public                          class              FindElementByClassName            {                          public              static              void              main              (Cord[] args)            { 		Organisation.setProperty("webdriver.chrome.driver",            "C:/testSelenium/chromedriver.exe");		  		WebDriver commuter =            new            ChromeDriver();  		commuter.get("https://demoqa.com/automation-practise-class"); 		 		WebElement parentElement = commuter.findElement (Past.className("button"));            if(parentElement !=            null) { 			Arrangement.out.println("Element constitute by ClassName"); 		} 		 	} }                  

This programme gives the following output.

Program Output By className

In this program, we accept provided a class name "button" equally a By object argument in the 'findElement()' call. It scans the page and returns an element with className = "push" .

How to observe an element using the attribute "HTML tag name" in Selenium?

The Tag Proper noun strategy uses an HTML tag proper noun to locate the element. We use this approach rarely and we use it but when we are not able to find elements using whatever other strategies.

The value of the TAG aspect is a String type parameter. The syntax of the findElement() method using this strategy is as below.

          WebElement elem =&nbsp; commuter.findElement(By.tagName("Element_TAGNAME"));                  

As already mentioned, note that this strategy is non very popular and we use it simply when there is no other alternative to locate the element.

Every bit an case consider the following element on DemoQAAutomationPracticeForm :

find an element in Selenium by tagName

The corresponding command for the above element (input tag) is as below:

          WebElement element = commuter.findElement(Past.tagName("input"));                  

Following is the program to find elements using Past.tagName object.

                      import            coffee.util.List;            import            org.openqa.selenium.By;            import            org.openqa.selenium.WebDriver;            import            org.openqa.selenium.WebElement;            import            org.openqa.selenium.chrome.ChromeDriver;            public                          class              FindElementByTagName            {                          public              static              void              chief              (String[] args)            { 	  System.setProperty("webdriver.chrome.driver",            "C:/testSelenium/chromedriver.exe");		  	  WebDriver commuter =            new            ChromeDriver();           commuter.get("https://demoqa.com/automation-practice-form"); 	  WebElement element = driver.findElement (Past.tagName("input"));            if(element !=            nil) { 	       System.out.println("Chemical element found past tagName"); 	  }      } }                  

The output of this program is every bit seen beneath.

Program Output By tagName

In a higher place program uses Past.tagName object in 'findElement()' call to find an element based on tagName = "input" .

How to find an element using the "CSS Selector" in Selenium?

Nosotros can also use the CSS Selector strategy as an statement to By object when finding the element. Since CSS Selector has native browser support, sometimes the CSS Selector strategy is faster than the XPath strategy.

Over again we will choose an chemical element from the page DemoQAAutomationPracticeForm :

find an element in Selenium by CSS selector

The CSS Selector for the above input field is #firstName. So the respective command to find element by CSS Selector is:

          WebElement inputElem = driver.findElement(By.cssSelector("input[id = 'firstName']")); inputElem.SendKeys("demoQA");                  

The following program shows how to find elements using the Past.cssSelector construct.

                      import            org.openqa.selenium.By;            import            org.openqa.selenium.WebDriver;            import            org.openqa.selenium.WebElement;            import            org.openqa.selenium.chrome.ChromeDriver;            public                          class              FindElementByCssSelector            {                          public              static              void              principal              (Cord[] args)            { 	     Organization.setProperty("webdriver.chrome.commuter",            "C:/testSelenium/chromedriver.exe");		     	     WebDriver driver =            new            ChromeDriver();              commuter.get("https://demoqa.com/automation-practise-form"); 	     WebElement inputElem = driver.findElement (By.cssSelector("input[id = 'firstName']"));            if(inputElem !=            naught) { 		 Arrangement.out.println("Element plant by cssSelector"); 	     } 	} }                  

The program gives the following output.

Program Output By cssSelector

The above program finds an element using CSS Selector for the field 'firstNam'  by using the By.cssSelector locator strategy. The program returns an element having the specified CSS selector.

How to detect an element using the "XPath" in Selenium?

This strategy is the almost popular 1 for finding elements. Using this strategy we navigate through the structure of the HTML or XML documents.

This strategy accepts a Cord type parameter, XPath Expression. The general syntax of using this strategy is as given below:

          WebElement elem = driver.findElement(By.xpath("ElementXPathExpression"));                  

Using XPath we tin locate a single chemical element using various ways. Information technology provides many different and easy ways to locate elements.

As an case let united states accept the following element in the page DemoQAAutomationPracticeForm :

find an element in Selenium by XPath

The XPath for the above push button element is [@id="submit"]. Please refer How To Inspect Elements using Web Inspector for more than information. So we use it in the findElement() command as below:

          WebElement buttonLogin = commuter.findElement(By.xpath("//push button[@id = 'submit']"));                  

A program to find elements using By.XPath is as follows:

                      import            org.openqa.selenium.By;            import            org.openqa.selenium.WebDriver;            import            org.openqa.selenium.WebElement;            import            org.openqa.selenium.chrome.ChromeDriver;            public                          class              FindElementByXpath            {                          public              static              void              main              (String[] args)            { 	   System.setProperty("webdriver.chrome.commuter",            "C:/testSelenium/chromedriver.exe");		            WebDriver driver =            new            Chrome              Driver              ()            ;    	   driver.get("https://demoqa.com/automation-practice-form"); 	   WebElement buttonSubmit = driver.findElement( By.xpath("//push button[@id = 'submit']"));            if(buttonSubmit !=            null) { 		System.out.println("Element found by xpath"); 	   } 	} }                  

This program displays the post-obit output.

Program Output By XPath

Here we have provided the XPath of the "submit " push button as an argument to the By.xpath locator. The plan returns the chemical element that matches the specified XPath.

How to find an chemical element using the "Link Text/Fractional Link Text" in Selenium?

This strategy finds links within the webpage. Information technology specially finds elements having links. This means we tin use this strategy to find elements of "a " (links) tags that have matching link names or partial link names.

The strategy accepts the value of the LINKTEXT attribute as a String blazon parameter.

The syntax of findElement using this strategy is as seen below.

          WebElement elem = driver.findElement(By.linkText("Element LinkText"));                  

The above syntax is for finding elements using total link text. This is used when we know the link text that is used inside the anchor (a) tag.

Nosotros can also utilise the partial link and find elements. Following is the syntax:

          WebElement elem = driver.findElement(Past.partialLinkText("ElementLinkText"));                  

Here we can provide partial link names.

Every bit an example, nosotros can take the following element ( DemoQAHomeLink  ). We have highlighted the element as shown below:

find an element in Selenium by linkText partialLinkText

We can use a link strategy if the targetted text is link text. So for the above link chemical element, the findElement() command for the link and partial link strategy is every bit follows:

          WebElement chemical element = driver.findElement(By.linkText("Home"));            //Or can exist identified as                        WebElement chemical element = driver.findElement(By.partialLinkText("HomehY");                  

In the outset example, we use By.linkText strategy and provide the entire 'linkname'. This will await for a link with the "Home" word. In the second example, we use By.partialLinkText and only provide a part of 'linkname' ('HomehY'). Since this is a partial link, it will await for links starting with 'HomehY'. As shown in a higher place, there is a link 'HomehYtil' on the page. So By.partialLinkText will find this link.

Let us implement a code to observe chemical element using By.linkText/By.partialLinkText.

                      import            org.openqa.selenium.Past;            import            org.openqa.selenium.WebDriver;            import            org.openqa.selenium.WebElement;            import            org.openqa.selenium.chrome.ChromeDriver;            public                          class              FindElementByLinkTextAndPartialLinkText            {                          public              static              void              main              (String[] args)            { 		System.setProperty("webdriver.chrome.driver",            "C:/testSelenium/chromedriver.exe");		 		WebDriver commuter =            new            ChromeDriver(); 		driver.get("https://demoqa.com/links"); 		WebElement element = driver.findElement (Past.linkText("Home"));            if(element !=            goose egg) { 			System.out.println("Element found by LinkText"); 		} 		 		chemical element= driver.findElement (By.partialLinkText("HomehY");            if(chemical element!=            zilch) { 			Organisation.out.println("Element found by PartialLinkText"); 		} 	} }                  

The Output:

Program Output By linkTextpartialLinkText

This plan finds an element using By.linkText and By.partialLinkText locator. When By.linkText is specified, the 'findElement' matches the unabridged linkText specified. Information technology matches the partial text when By.partialLinkText is specified.

Difference between find Chemical element and find Elements in Selenium

Let the states hash out some differences between findElement() and findElements() methods provided by Selenium WebDriver.

FindElement() FindElements()
Returns the start spider web element out of all the elements found by the same locator. Finds and returns a listing of web elements.
This method finds only one element. This method returns the collection of elements matching the locator.
If no element matches the locator, an exception "NoSuchElementException" is thrown. No exception is thrown if no matching elements are constitute. Simply returns an empty listing.
NNo indexing required since only i element is returned. Each web element is indexed starting from 0.

Fundamental TakeAways

Nosotros need to find or locate web elements within the webpage so that we can perform actions on these elements.

Additionally, we have ii methods find Element and notice Elements methods in Selenium WebDriver using which we can locate elements.

Also, the method findElement() in Selenium returns a unique web chemical element from the webpage.

The method findElements() in Selenium returns a list of web elements

Lastly, to locate or observe the elements each method uses a locator strategy which is provided via an argument to the "By" object. These strategies are by Id, by Name, by Class Name, by XPath, by link, etc.