Explore the world of Selenium with our in-depth tutorial. Whether you’re a beginner or an experienced developer, our Selenium tutorial provides step-by-step guidance to enhance your automation skills. Join us for the best Tutorial Selenium experience!: Effective Element Locators and Automation Techniques
Tutorial Selenium: What is Selenium ?
Selenium is a free (open-source) automated testing suite for web applications across different browsers and platforms. Selenium focuses on automating web-based applications.
Tutorial Selenium
Note: Selenium is one of the most popular automated testing suites. Selenium is designed in a way to support and encourage automation testing of functional aspects of web-based applications and a wide range of browsers and platforms. Due to its existence in the open-source community, it has become one of the most accepted tools among testing professionals.
Table of Contents: For Tutorial Selenium
Tutorial Selenium: Selenium is not just a single tool but a suite of software, each catering to the different testing needs of an organization. It has four components.
- Selenium Integrated Development Environment (IDE).
- Selenium Remote Control (RC).
- Web Driver.
- Selenium Grid.
- WebDriver
- It is a free and open-source web application automation tool, which performs the action on the Application by calling native methods of the browser.
WebDriver
- It is an interface; it will be inheriting from the Search context interface.
Remote WebDriver
- Remote WebDriver Class implements all the abstract methods of the both interface.
- The browser specific class such as Firefox, Chrome driver, internet explorer driver, safari driver, extends Remote WebDriver class.
Launch Browser
Selenium offers powerful options through `ChromeOptions` and `EdgeOptions` that allow you to customize and optimize your test scenarios. 🛠️
ChromeOptions
// Create ChromeOptions instance
ChromeOptions options = new ChromeOptions();
// Add options
options.addArguments(“–start-maximized”); // Maximize the browser window
options.addArguments(“–disable-extensions”); // Disable browser extensions
options.addArguments(“–incognito”); // Launch in incognito mode
// Launch Chrome WebDriver with custom options
WebDriver driver = new ChromeDriver(options);
EdgeOptions
// Create EdgeOptions instance
EdgeOptions options = new EdgeOptions();
// Add options
options.addArguments(“–start-maximized”); // Maximize the browser window
options.addArguments(“–disable-extensions”); // Disable browser extensions
options.addArguments(“–incognito”); // Launch in incognito mode
// Launch Edge WebDriver with custom options
WebDriver driver = new EdgeDriver(options);
Use following code-
WebDriver driver=WebDriverManager.chromedriver().setup();
ChromeOptions options = new ChromeOptions();
options.addArguments(“- -remote-allow-origins=*”);
driver =new ChromeDriver(options);
Below Code for Launch a Chrome Browser:
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import io.github.bonigarcia.wdm.WebDriverManager;
public class BrowserLaunchExample {
public static void main(String[] args) {
// Setup WebDriverManager for Chrome
WebDriverManager.chromedriver().setup();
// Create an instance of ChromeDriver
WebDriver driver = new ChromeDriver();
// Launch the browser
driver.get(“https://www.example.com”);
// Close the browser
driver.quit();
}}}
What is the difference between close () & quit ()?
Close () – It is used to close the browser or page currently which is having the focus.s
Quit () – It is used to shut down the web driver instance or destroy the web driver instance (Close all the windows).
WebDriver Commands
Launch URL
- Where appUrl is the website address to load. It is best to use a fully qualified URL.
- Command – driver.get(“URL”);
GetTitle ():
This method fetches the Title of the current page. Accepts nothing as a parameter and returns a String value.
Command – driver.getTitle();
WebDriver driver = new FirefoxDriver();
driver.get(“http://www.Google.com”);
String Title = driver.getTitle();
System.out.println(Title);
Get Current URL Command
- getCurrentUrl () : String
- This method fetches the string representing the Current URL which is opened in the browser. Accepts nothing as a parameter and returns a String value.
Command – driver.getCurrentTitle ();
Get Page Source Command
- getPageSource (): String
- This method returns the Source Code of the page. Accepts nothing as a parameter and returns a String value.
Command – driver.getPageSource ();
Browser Navigation Commands
- We have 5 navigation methods, those are
- Back ()
- Forward ()
- Refresh ()
- Two overloaded ‘to’ methodsTo
Click here for Learn Manual testing concepts
Examples:
- driver. navigate().to(“http://www.bing.com”);
- driver. navigate().to(“http://www.gmail.com”);
- driver. navigate().back();
- driver.navigate ().refresh ();
Cookie
Add Cookie
“//we should pass name and value for cookie as parameters”
“// In this example we are passing, name=my cookie and value=123456789123”
Cookie name = new Cookie(“mycookie”, “123456789123”);
driver.manage().addCookie(name);
“// After adding the cookie we will check that by displaying all the cookies.”
Set<Cookie> cookiesList = driver.manage().getCookies();
for(Cookie getcookies :cookiesList) {
System.out.println(getcookies );
}
Delete cookie :
Cookie name = new Cookie(“cookie”, “1234”);
driver.manage().deleteCookieNamed(“cookie”);
Delete all cookies
driver.manage().deleteAllCookies();
Locators In selenium 4
Relative Locators, were introduced in Selenium 4 to make it easier to locate elements based on their relationship with other elements. The primary methods in the RelativeLocator class include near(), above(), below(), toRightOf(), and toLeftOf().
1. Near:
The near() method is used to locate an element near another element.
WebElement element = driver.findElement(RelativeLocator.withTagName(“div”).near(referenceElement));
2. Above:
The above() method is used to locate an element above another element.
WebElement element = driver.findElement(RelativeLocator.withTagName(“div”).above(referenceElement));
3. Below:
The below() method is used to locate an element below another element.
WebElement element = driver.findElement(RelativeLocator.withTagName(“div”).below(referenceElement));
4. ToRightOf:
The toRightOf() method is used to locate an element to the right of another element.
WebElement element = driver.findElement(RelativeLocator.withTagName(“div”).toRightOf(referenceElement));
5. ToLeftOf:
The toLeftOf() method is used to locate an element to the left of another element.
WebElement element = driver.findElement(RelativeLocator.withTagName(“div”).toLeftOf(referenceElement));
It’s important to note that Relative Locators are specific to Selenium 4 and may not be available in earlier versions. Before using them, ensure that your Selenium WebDriver version is compatible with Selenium 4.
Locators:
used to identify the location of the WebElement in the webpage
There are Eight type of locators are there
Sr No | Method |
---|---|
1 | id() |
2 | name() |
3 | className() |
4 | linkText() |
5 | partialLinkText() |
6 | CSS Selectors() |
7 | XPath() |
8 | tagName() |
1. id():
Used to identify the location of the WebElement by using id attribute value.
Example:
driver.findElement(By.id(“username”)).click();
2.Name():
Used to identify the location of the webElement by using Name Attribute value.
Example:
driver.findElement(By.name(“pwd”)).sendKeys(“manager”);
3.ClassName():
Used to identify the location of the webElement by using ClassName Attribute value.
Example:
driver.findElement(By.className(“pwdfield”)).sendKeys(“manager”);
4.By LinkText(String VisibleText):
Used to identify the location of the webElement by using complete visible Test value.
This locators only works with <a>.
Example:
driver.findElement(By.LinkText(“Forget your password?”)).click();
5.By PartialLinkText(String Partial VisibleText):
Used to identify the location of the webElement by using partial visible Test value.
Example:
driver.findElement(By.partialLinkTest(“forget your”)).click();
6.By CSS Selector(String CSS Expression):
Used to identify the location of the WebElement by using CSS expression.
Example:
driver.findElement(By.cssSelector(“a[id=’Login Button’]”)).click();
7.X-path:
We can search the WebElement in html tag,attribute and Visible Test.
There are two types:
1.Absolute x-path:
Used to identify the location of Static WebElement
Example:
driver.findElement(By.xpath(“/html/body/input[7]”)).click();
2.Relative x-path:
Used to identify the location of dynamic WebElement.
Example:
driver.findElement(By.xpath(“//span[contains(text(),’Showing’)]”)).getText();
8.TagName:
Used to identify the location of the webElement by using tagname.
Example:
driver.findElement(By.tagName(“label”)).click();
Selenium Waits
In Selenium WebDriver, implicit wait, explicit wait, and fluent wait are mechanisms to manage the timing of interactions with web elements to handle synchronization issues. Here’s an explanation and example of each in Java:
1. Implicit Wait:
Implicit wait is set globally for the entire duration of the WebDriver object. It instructs the WebDriver to wait for a certain amount of time before throwing a . It is set once and affects all subsequent find element calls.
// Set implicit wait to 10 seconds
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
2. Explicit Wait:
Explicit wait allows you to wait for a certain condition to occur before proceeding further in the code. It is more specific than implicit wait and is applied to a particular element or condition.
/Explicitly wait for an element to be clickable
WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement element = wait.until(ExpectedConditions.elementToBeClickable(By.id(“someElement”)));
3. Fluent Wait:
Fluent wait is similar to explicit wait but provides more flexibility. It allows you to define a custom polling strategy, ignoring specific exceptions, and waiting for a certain condition.
/ Fluent wait with a custom polling interval and timeout
FluentWait<WebDriver> wait = new FluentWait<>(driver)
.withTimeout(Duration.ofSeconds(10))
.pollingEvery(Duration.ofMillis(500))
.ignoring(NoSuchElementException.class);
WebElement element = wait.until(ExpectedConditions.elementToBeClickable(By.id(“someElement”)));
Launch a Chrome browser
To launch Chrome with Chrome options in Selenium using WebDriverManager in Java, you can use the following code. Ensure you have the WebDriverManager library added to your project:
import io.github.bonigarcia.wdm.WebDriverManager;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
public class ChromeWithOptionsExample {
public static void main(String[] args) {
// Setup Chrome options
ChromeOptions chromeOptions = new ChromeOptions();
// Add desired Chrome options
chromeOptions.addArguments("--start-maximized"); // Maximize the browser window
chromeOptions.addArguments("--disable-extensions"); // Disable browser extensions
chromeOptions.addArguments("--disable-infobars"); // Disable the 'Chrome is being controlled by automated test software' message
// Set up WebDriverManager for Chrome
WebDriverManager.chromedriver().setup();
// Create a new ChromeDriver with the configured Chrome options
WebDriver driver = new ChromeDriver(chromeOptions);
// Navigate to a website (replace "https://example.com" with your desired URL)
driver.get("https://example.com");
// Perform your Selenium actions here
// Close the browser
driver.quit();
}
}
Explore our in-depth Tutorial Selenium series for mastering automation and testing. Stay connected for continuous learning and updates on Selenium tutorials. Enhance your skills with our ongoing tutorials!