The findElement() and findElements() methods in Selenium
Overview
Selenium is a powerful tool for programmatically manipulating an internet browser. All major browsers can use it, it runs on all major operating systems, and it has scripts written in many different languages, including Python, Java, C#, and others.
Add the following dependency to pom.xml.
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>4.3.0</version>
</dependency>
The findElement() method
The findElement() method is used to find the first web element matching the given selector.
Syntax
drive.findElement(selector)
Code
public class Main{public static void main (String[] args) {System.setProperty("webdriver.gecko.driver","path to driver");String url = "https://educative.io/";WebDriver driver = new FirefoxDriver();driver.get(url);String tagName = "title";String title = driver.findElement(By.tagName(tagName)).getText();System.out.println("The title of " + url + " is " + title);driver.close();}}
Explanation
- Line 4: We set the system property webdriver.gecko.driver to point to the firefox driver.
- Line 5: The URL to be opened is defined.
- Line 6: This is the instance of the FirefoxDriver that is defined.
- Line 7: We use the
get()method to open the URL/webpage. - Line 8: We define the tag name.
- Line 9: We use the tag name, with the help of the
findElement()method to retrieve the web element. Then, we use thegetText()method to to retrieve the text of the element. - Line 10: We print the retrieved text.
- Line 11: The driver is closed.
The findElements() method
The findElements() method is used to find all the web elements matching the given selector.
Syntax
drive.findElements(selector)
Code
public class Main{public static void main (String[] args) {System.setProperty("webdriver.gecko.driver","path to driver");String url = "https://educative.io/";WebDriver driver = new FirefoxDriver();driver.get(url);String tagName = "a";List<WebElement> allLinks = driver.findElements(By.tagName(tagName));for(WebElement link:allLinks){System.out.println(link.getText() + " - " + link.getAttribute("href"));}driver.close();}}
Explanation
- Line 4: We set the system property webdriver.gecko.driver to point to the Firefox driver.
- Line 5: We define the URL.
- Line 6: We define an instance of the FirefoxDriver.
- Line 7: We use the
get()method to open the URL/webpage. - Line 8: We define the tag name.
- Line 9: We use the tag name, with the help of the
findElements()method, to retrieve the web elements. - Line 10: For every web element extracted in line 9, we use the
getTextmethod to get the text. Then we use thegetAttribute()method to get the value of thehrefattribute. - Line 11: We close the driver.