Check out my iOS apps here
As an Amazon Associate I earn from qualifying purchases.

How to Find Web Elements in Selenium Web Driver with Java tutorial (With examples).

There Are Many Ways To Locate Web Elements In A Web Page Using Selenium Web Driver

Before we get to interact with the various elements on the web page, like filling textboxes or clicking on buttons, we have to locate them & store them in variables. There are many ways to do so, either by using the tag name, the ID or the CSS class of the element. Also, there are other elements locators that makes it easier to locate elements in more sophisticated ways. In this lesson, we will look at all these ways one by one.

This lesson is part of a series about Selenium Web Driver. You can go to the first part in the series by clicking here.

Findelement VS Findelements:- Locating One Or More Elements

There are two functions used to find elements with Selenium Web Driver:- FindElement & FindElements. Both functions locate elements the same way, except there are few differences:-

    • FindElement locates & returns only one element. If there are multiple elements that matches the criteria, it will return the first one.
    • FindElements locates all the elements that matches the criteria you specified.

You could use FindElement when you know there’s only one element that matches what you’re looking for, like when you locate an element using its ID, or when you don’t care which elements out of many you end up getting.

Both functions are used the same way, FindElement will return a WebElement object, while FindElements finds a list of WebElement (List).

You can use any of the two functions depending on what you need. I will show you one example on how to use FindElements to iterate through multiple elements later in this lesson.

How To Use Findelement() To Locate Elements

FindElement takes one parameter of type By. The By locator tells the FindElement function how to locate the element.

There are two kinds of locators, simple locators and the more sophisticated ones. The simple locators find elements by simply matching the ID, tag name, the name attribute with the value you provide. The more sophisticated locators allow you to locate elements in a more intricate ways:-

    • You could use them to locate elements using any attribute you want, either by fully or partially matching the attribute value.
    • They also allow you to find elements based on the parent tag.
    • Find elements that matches multiple conditions, instead of just one.

If you mastered these sophisticated locators, you won’t need to use the simple locators at all if you want. The sophisticated locators are called CSS Selector & XPath.

Let’s take a look at all the locators of Web Driver.

By Tag Name

Example:- By.tagName(“name”);

The tag name locator finds element by tag name. For example, to locate the Title tag in the page, you could use By.tagName(“title”);. The same way, you could also use driver.findElements(By.tagName(“input”)) to get a list with all the input elements in the page.

By ID

Example:- By.id(“id”);

The ID locator locates elements based on the ID attribute. That is useful for finding a very specific element, since the ID is supposed to be unique, and two elements can’t have the same ID. Unlike some of the other attributes, like the tag name or class name, which can be shared by multiple elements.

It’s worth noting that while ID is supposed to be unique, in some badly-designed sites, there could be multiple elements with the same ID. That could cause some issues in your code, so keep that in mind.

By Class Name

Example:- By.className(“ClassName”)

If you know the class name of the element you’re locating, then you can use it to locate that element. Since class names to stay the same for a while in most websites, this makes it easier to locate an element even after its location in the HTML has changed. Just be sure to use a class name that’s unique enough.

Bear in mind that Selenium doesn’t work well with compound class names, which are elements with multiple classes (e.g. class=”LeftAligned Button”), so in that case, you may want to use some other locator to locate elements with such classes. Using XPath is an options here.

By Link Text

Example:- By.linkText(“linkText”);

LinkText locates link(s) based on its text. For example, if a link text is Click here, you could locate it by passing By.linkText(“Click here”) to the FindElement function.

By Partial Link Text

Example:- By.partialLinkText(“linkText”);

Partial Link Text is similar to the link text locator, except that you only need to specify part of the link text. If a link text is Click here to view the article, you could locate that element using By.partialLinkText(“Click here”). This locator is quite useful when the element text may not be fully known, or if you want to write Selenium program that would work even if the website underwent some changes.



By Name

Example:- By.name(“name”);

This locator takes a string that matches the name attribute of the elements (as in name=”some attribute”). Since many sites use that attribute in their elements. This can be quite useful in locating radio buttons, which uses the name attribute.

By CSS Selector

Example:- By.cssSelector(“selector”);

All the locators we have seen so far are simple. They allow you to locate elements in one way or another, like matching the ID or tag name. But there are times where you want to find elements in a more sophisticated way. Web Pages uses CSS all the time to style the elements, and we could take advantage of these styles to locate them. For example, the CSS selector “div img” locates the IMG elements that directly falls under a DIV tag.

CSS Selectors tend to be fast, which makes it the best option to locate elements in a lot of cases. It’s even better than XPath (and easier to type), which we will take a look at right after this.

Some Examples Of CSS Selector:-

    • By.cssSelector(“.SubTitle”):- Locates all the elements with the class name “SubTitle”
    • By.cssSelector(“.ContentIndex .InlineElements”):- Locates all the elements with the class name “InlineElements”, whose parent has the class name “ContentIndex” (notice there’s a space between the two)
    • By.cssSelector(“.ClassName1.ClassName2”) (No space between the two class names):- Locates the element with both classes “ClassName1” & “ClassName2”.
    • By.cssSelector(“#ThisIsID”):- Locates the element with the ID “ThisIsID”.
    • By.cssSelector(“*”):- Locates all elements.
    • By.cssSelector(“div p”):- Locates all the P elements whose parent is a div element.
    • By.cssSelector(“div div p”):- Locates all the P elements whose parent is a div element. And that div element also has a div element.
    • By.cssSelector(“a[href*=\”Fairy\”]”):- Locates all the links (a elements) that contains “Fairy” in the href attribute (which is the url of the link).
    • By.cssSelector(“div::before”):- Locates the elements prior to div elements
    • By.cssSelector(“div::after”):- Locates the elements next to div elements

CSS Selector is so powerful that it requires a dedicated lesson on its own. ☇

By Xpath

Example:- By.xpath(“XPathExpression”);

XPath finds elements using XPath, which stands for XML Path language. It’s a powerful language for locating Web Elements in various ways. Be it tag name, parent tag, attribute name/value or a combination of them, including the attribute not covered by the simple locators. It’s a very powerful language that allows you to forgo all the other locators if you so wanted. Although XPath can be slow, so you probably should avoid using it if you can, specially if performance is a concern. However, it is a powerful way to create flexible tests that work even if the page underwent many changes, specially when performance isn’t a top priority.

Here Are Some Examples Of Xpath Expressions:-

    • By.xpath(“/html/body/div”):- Locates all the div elements under the body tag, which are naturally located under the HTML tag.
    • //div:- Locates all the divs in the page. The fact the XPath starts with // means the located element can be anywhere in the HTML. Unlike the XPath expressions starting with /, which indicates the XPath is an absolute path.
    • //div/img:- Locates all the img tags under any div tag on the page.
    • //h2[contains(text(),’Tenkey Keyboards’)]:- Locates all the h2 headers with “Tenkey Keyboards” in their text.
    • //div[@class=’ContentIndex’]:- Locates any div element with the class name “ContentIndex”.
    • //div[contains(@class , ‘Content’)]:- Locates any div element whose class name contains the word “Content”.

Just like CSS Selectors, XPath is so powerful it requires a dedicated lesson on its own☇.

Practical Example:- Finding Multiple Elements And Iterating Through Them.

In this example, we will write a Java code that visits The Practice Image Gallery, and locates all the IMGs elements using the findElements() method, then iterate through them & print their image URL. The URL is found in the src attribute of each IMG tag, which can be obtained using the getAttribute() function of WebElement. The code indiscriminately selects all the images in the page, including some images we don’t want, like the site logo, and some other images. You could write a code that filter those images out if we so like, using their dimensions or other attributes, or do anything else we want with them.

Here’s the code:-

String GeckoPath = "C:\\Fairy\\geckodriver.exe";
System.setProperty("webdriver.gecko.driver", GeckoPath);
WebDriver driver = new FirefoxDriver();
driver.get("https://tech-fairy.com/selenium-webdriver-paractice-images-gallery/");
List IMGEelements = driver.findElements(By.tagName("img"));
for (WebElement IMG : IMGEelements) {
String ImageSource = IMG.getAttribute("src");
System.out.println(ImageSource);
} // For
// The line to close the driver is commented, since you may want to check the results on your own
//		driver.close();

Locating Nested Webelements Using The Parent

The FindElement & FindElements functions of the WebDriver searches thorough the whole page for the element that matches your criteria. Objects of the type WebElement also have the same functions, except that they only search through the children & descendents of the element. Other than that, they work in the exact same way, so we could apply everything we learned about locating elements to them.

This can be so useful, because sometimes it’s easier to locate the WebElement by locating the parent Element first, then search through its children by calling FindElement or FindElements of that parent. That’s particularly the case when you don’t want to use Xpath or CSS Selector for that.

Finding The Submit Button From Inside The Form Element

To demonstrate finding elements inside the parent element, we will use our practice login form, we will locate the form element first, then locate the submit button inside of it using its class name.

Here’s the whole code that does all that:-

String GeckoPath = "C:\\Fairy\\geckodriver.exe";
System.setProperty("webdriver.gecko.driver", GeckoPath);
WebDriver driver = new FirefoxDriver();
driver.get("https://tech-fairy.com/selenium-webdriver-paractice-log-in-form/");
WebElement FormElement = driver.findElement(By.tagName("form"));
WebElement SubmitButton = FormElement.findElement(By.className("MainButton"));
SubmitButton.click();
// The line to close the driver is commented, since you may want to check the results on your own
//		driver.close();

And Finally

I hope my lesson has helped you learn about locating elements using Selenium Web Driver, and see you again in another one.

See Also:-

Leave a Comment

Your email address will not be published. Required fields are marked *