Introduction to Selenium
Selenium WebDriver Basics
WebDriver Commands
Synchronization in Selenium
Working with Different Browsers
Setting up WebDriver for different browsers
Handling Advanced User Interactions
Page Object Model (POM)
Introduction to POM
TestNG Framework
Creating and Running TestNG Tests

Selenium Tutorial

Selenium: A Comprehensive Introduction

What is Selenium?

Selenium is a powerful, open-source tool used for automating web browsers. It is primarily used for automating web applications for testing purposes but is not limited to just that. Selenium can also be used to automate repetitive web-based tasks.

History of Selenium

  • 2004: Selenium was originally developed by Jason Huggins at ThoughtWorks as an internal tool to test web applications.
  • 2006: Selenium RC (Remote Control) was developed, which allowed for more flexible and advanced testing.
  • 2008: Selenium WebDriver was introduced by Simon Stewart, which provided a simpler and more powerful API for automating browser actions.
  • 2011: Selenium 2.0 was released, combining WebDriver and Selenium RC.
  • 2018: Selenium 4.0 was announced, introducing new features and improvements over the previous versions.

Components of Selenium

  1. Selenium IDE (Integrated Development Environment)

    • A Firefox/Chrome extension that allows users to record and playback browser interactions.
    • Best for quick bug reproduction scripts and exploratory testing.
  2. Selenium WebDriver

    • A programming interface to create and execute test scripts.
    • Supports multiple programming languages like Java, C#, Python, Ruby, and JavaScript.
    • Provides support for multiple browsers (Chrome, Firefox, IE, Safari, etc.).
  3. Selenium Grid

    • Used to run tests on multiple machines and browsers simultaneously.
    • Supports distributed test execution, reducing test execution time.
  4. Selenium RC (Remote Control)

    • An older tool that allowed more flexible testing but has been deprecated in favor of WebDriver.

Selenium WebDriver Architecture

Selenium WebDriver follows a client-server architecture where:

  • The client is the test script written in any supported programming language.
  • The server is the browser driver (e.g., ChromeDriver for Chrome, GeckoDriver for Firefox) that interacts with the browser.

WebDriver's workflow:

  1. The client sends commands to the WebDriver.
  2. WebDriver translates these commands into HTTP requests and sends them to the browser driver.
  3. The browser driver executes these requests on the browser and sends back the response.

Setting Up Selenium WebDriver

Environment Setup:

  • Java: Ensure you have JDK installed.
  • IDE: Use an Integrated Development Environment like Eclipse or IntelliJ IDEA.
  • Selenium WebDriver: Download the WebDriver library from the Selenium website.
  • Browser Drivers: Download the appropriate drivers (e.g., ChromeDriver, GeckoDriver).

Adding Selenium to Your Project:

  • Add the Selenium WebDriver JAR files to your project’s build path.

Writing Your First Selenium Script

Here is an example using Java

Setup Project:
  • Create a new Java project in your IDE.
  • Add Selenium WebDriver JAR files to the project’s build path.
Basic Script:
				
					import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class FirstSeleniumScript {
    public static void main(String[] args) {
        // Set the path to the ChromeDriver executable
        System.setProperty("webdriver.chrome.driver", "path/to/chromedriver");

        // Create a new instance of the Chrome driver
        WebDriver driver = new ChromeDriver();

        // Launch the browser and navigate to a website
        driver.get("http://www.example.com");

        // Print the title of the webpage
        System.out.println("Title: " + driver.getTitle());

        // Close the browser
        driver.quit();
    }
}

				
			
selenium tutorial

Locating Web Elements

Selenium provides several ways to locate elements on a web page:

1. By ID

				
					WebElement element = driver.findElement(By.id("elementId"));

				
			

2. By Name:

				
					WebElement element = driver.findElement(By.name("elementName"));

				
			

3. By Class Name:

				
					WebElement element = driver.findElement(By.className("elementClass"));


				
			

4. By Tag Name:

				
					WebElement element = driver.findElement(By.tagName("elementTag"));


				
			

5. By Link Text:

				
					WebElement element = driver.findElement(By.linkText("Link Text"));



				
			

6. By Partial Link Text:

				
					WebElement element = driver.findElement(By.partialLinkText("Partial Link"));




				
			

7. By CSS Selector:

				
					WebElement element = driver.findElement(By.cssSelector("cssSelector"));




				
			

8. By XPath:

				
					WebElement element = driver.findElement(By.xpath("xpathExpression"));





				
			

WebDriver Commands

1. Browser Commands:

				
					driver.get("http://www.example.com");
driver.navigate().to("http://www.example.com");
driver.navigate().back();
driver.navigate().forward();
driver.navigate().refresh();
driver.quit();

				
			

2. Web Element Commands:

				
					WebElement element = driver.findElement(By.id("elementId"));
element.click();
element.sendKeys("text to type");
element.clear();
String text = element.getText();

				
			

Synchronization in Selenium

1. Implicit Wait:

				
					driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

				
			

2. Explicit Wait:

				
					WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement element = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("elementId")));

				
			

3. Fluent Wait:

				
					Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
    .withTimeout(30, SECONDS)
    .pollingEvery(5, SECONDS)
    .ignoring(NoSuchElementException.class);

WebElement element = wait.until(new Function<WebDriver, WebElement>() {
    public WebElement apply(WebDriver driver) {
        return driver.findElement(By.id("elementId"));
    }
});

				
			

Handling Different Browsers

1. Chrome:

				
					System.setProperty("webdriver.chrome.driver", "path/to/chromedriver");
WebDriver driver = new ChromeDriver();

				
			

2. Firefox:

				
					System.setProperty("webdriver.gecko.driver", "path/to/geckodriver");
WebDriver driver = new FirefoxDriver();

				
			

3. Internet Explorer:

				
					System.setProperty("webdriver.ie.driver", "path/to/IEDriverServer");
WebDriver driver = new InternetExplorerDriver();

				
			

4. Edge:

				
					System.setProperty("webdriver.edge.driver", "path/to/msedgedriver");
WebDriver driver = new EdgeDriver();

				
			

5. Safari:

				
					WebDriver driver = new SafariDriver();

				
			

Handling Advanced User Interactions

1. Mouse Actions:

				
					Actions actions = new Actions(driver);
actions.moveToElement(element).perform();
actions.contextClick(element).perform();
actions.doubleClick(element).perform();
actions.dragAndDrop(sourceElement, targetElement).perform();


				
			

2. Keyboard Actions:

				
					actions.sendKeys(Keys.ENTER).perform();
actions.keyDown(Keys.CONTROL).sendKeys("a").keyUp(Keys.CONTROL).perform();

				
			

Page Object Model (POM)

1. Creating Page Classes:

				
					public class LoginPage {
    WebDriver driver;

    @FindBy(id = "username")
    WebElement username;

    @FindBy(id = "password")
    WebElement password;

    @FindBy(id = "login")
    WebElement loginButton;

    public LoginPage(WebDriver driver) {
        this.driver = driver;
        PageFactory.initElements(driver, this);
    }

    public void login(String user, String pass) {
        username.sendKeys(user);
        password.sendKeys(pass);
        loginButton.click();
    }
}

				
			

2. Using Page Factory:

				
					WebDriver driver = new ChromeDriver();
LoginPage loginPage = new LoginPage(driver);
loginPage.login("user", "pass");

				
			

TestNG Framework

1. Introduction to TestNG:

  • TestNG is a testing framework inspired by JUnit and NUnit.
  • It provides annotations, flexible test configuration, and powerful execution features.

2. Writing TestNG Tests:

				
					import org.testng.annotations.Test;

public class TestClass {
    @Test
    public void testMethod() {
        System.out.println("This is a TestNG test method");
    }
}

				
			

3. Running Tests:

  • Create a testng.xml file to define test suites and test cases.
  • Run tests using the TestNG plugin in your IDE or from the command line.

Selenium Grid

1. Setting Up Selenium Grid:

Start the Hub:

				
					java -jar selenium-server-standalone.jar -role hub

				
			

Start the Node:

				
					java -jar selenium-server-standalone.jar -role node -hub

				
			

2. Configuring Tests to Run on the Grid:

				
					DesiredCapabilities capabilities = DesiredCapabilities.chrome();
WebDriver driver = new RemoteWebDriver(new URL("http://localhost:4444/wd/hub"), capabilities);

				
			

Data-Driven Testing

1. Using Excel for Data Storage (Apache POI):

				
					FileInputStream fis = new FileInputStream(new File("path/to/excelFile.xlsx"));
XSSFWorkbook workbook = new XSSFWorkbook(fis);
XSSFSheet sheet = workbook.getSheetAt(0);
Row row = sheet.getRow(0);
Cell cell = row.getCell(0);
String cellData = cell.getStringCellValue();
workbook.close();

				
			

Integration with Other Tools

1. Maven Integration:

Create a pom.xml file to manage dependencies:
				
					<dependencies>
    <dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-java</artifactId>
        <version>3.141.59</version>
    </dependency>
    <dependency>
        <groupId>org.testng</groupId>
        <artifactId>testng</artifactId>
        <version>6.14.3</version>
    </dependency>
</dependencies>

				
			

2. Jenkins Integration:

  • Install Jenkins and create a new job.
  • Configure the job to pull the project from a version control system (e.g., Git).
  • Add build steps to run the test cases.

3. Logging with Log4j

				
					import org.apache.log4j.Logger;

public class TestClass {
    static Logger log = Logger.getLogger(TestClass.class);

    public static void main(String[] args) {
        log.info("This is an info message");
        log.error("This is an error message");
    }
}

				
			

4. Reporting with Extent Reports:

				
					import com.aventstack.extentreports.ExtentReports;
import com.aventstack.extentreports.ExtentTest;
import com.aventstack.extentreports.reporter.ExtentHtmlReporter;

public class TestClass {
    public static void main(String[] args) {
        ExtentHtmlReporter htmlReporter = new ExtentHtmlReporter("extent.html");
        ExtentReports extent = new ExtentReports();
        extent.attachReporter(htmlReporter);

        ExtentTest test = extent.createTest("MyFirstTest", "Sample description");
        test.pass("Test passed");

        extent.flush();
    }
}

				
			

Selenium is a robust and versatile tool for automating web applications. It offers support for multiple browsers, programming languages, and platforms, making it an essential tool for developers and testers. Whether you are writing simple scripts or integrating with complex CI/CD pipelines, Selenium provides the flexibility and power needed to ensure the quality and reliability of your web applications.

Scroll to Top