WebDriver interface
provides number of methods to locate elements in a web page. You can locate an
element by using class name, id, name, linktext etc., In this post, I am going
to explain how to locate an element using class name.
For example, index.html is coded like below.
index.html
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <div class="header"> <h1>Simple application to demonstrate Selenium webdriver</h1> </div> <div class="header"> <p>WebDriver interface provides number of methods to locate elements in a web page. You can locate an element by using class name, id, name, linktext etc.,</p> </div> </body> </html>
Assume index.html is
running on url “http://localhost:8080/application”.
App.java
import java.util.List; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; public class App { public static void main(String[] args) { WebDriver driver = new FirefoxDriver(); driver.get("http://localhost:8080/application"); List<WebElement> elements = driver.findElements(By.className("header")); for (WebElement element : elements) { System.out.println(element.getTagName()); System.out.println(element.getText()); System.out.println("*************************\n"); } } }
Run above application,
you will get following output in the console.
div Simple application to demonstrate Selenium webdriver ************************* div WebDriver interface provides number of methods to locate elements in a web page. You can locate an element by using class name, id, name, linktext etc., *************************
List<WebElement> elements =
driver.findElements(By.className("header"));
Above statement locate
all elements within the current page, where class has value header.
element.getTagName()
Return the tag name of
the element.
element.getText()
Return the visible
innerText of this element.
No comments:
Post a Comment