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>
findElement()
methodThe findElement()
method is used to find the first web element matching the given selector.
drive.findElement(selector)
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();}}
get()
method to open the URL/webpage.findElement()
method to retrieve the web element. Then, we use the getText()
method to to retrieve the text of the element.findElements()
methodThe findElements()
method is used to find all the web elements matching the given selector.
drive.findElements(selector)
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();}}
get()
method to open the URL/webpage.findElements()
method, to retrieve the web elements.getText
method to get the text. Then we use the getAttribute()
method to get the value of the href
attribute.