Basic Selenium
Selenium is a free (open-source) automated testing framework used to validate web applications across different browsers and platforms. You can use multiple programming languages like Java, C#, Python, etc to create Selenium Test Scripts. Testing done using the Selenium testing tool is usually referred to as Selenium Testing. The programming language that I will be using here is Java.
Before you start follow this Installation and Setup for selenium guide https://www.guru99.com/installing-selenium-webdriver.html
After finish setup selenium, first step is set BrowserDriver -> System.setProperty(“webdriver.chrome.driver”, “path to your chromedriver.exe file in explorer”);
Example:
System.setProperty(“webdriver.chrome.driver”,”C:\\Users\\LENOVO\\Downloads\\chromedriver.exe”);
WebDriver driver = new ChromeDriver();
Open URL we want, in this case, I use Google
driver.get(“https://www.google.com/”);
Get Title of a Website
Make a new variable for the title which has value for getting the title.
String actualTitle = driver.getTitle();
How to make sure the Title is correct as expected?
if(actualTitle.contentEquals(“Google”)){
System.out.println(“Pass”);
} else {
System.out.println(“Fail”);
}
Finding Element By ID
Open Inspect Element (right-click, click Inspect) on a page of the website. Find the id on the element you want to search.
Here I have a screenshot of an inspect element from google.com
WebDriver element = driver.findElement(By.id(“id of element”));
Example:
WebDriver element = driver.findElement(By.id(“searchform”));
How to locate element using Xpath
What is XPath in Selenium? XPath is a technique in Selenium to navigate through the HTML structure of a page.
The basic using XPath is ->
WebDriver element = driver.findElement(By.xpath(“xpath of element”));
The question is, how to get this “xpath of element”?
- Right-click on the element you want to find and click Inspect
- Click CTRL-F on the Inspect Elements box, here you can make an Xpath. In that Element, you can see it has the tag “name”, so you can make your Xpath like this //input[@name=’q’]
And it will be like this
WebDriver element = driver.findElement(By.xpath(“//input[@name=’q’]”));
Select Option from dropdown menu
Select selectOpt = new Select (driver.findElement(By.id(“id each dropdown”));
selectOpt.selectByIndex(1);
Take Screenshot and save it as a file
You can use this script ->
TakesScreeshot scrShot = ((TakesScreenshot) driver);
File SrcFile = scrShot.getScreesnhotAs(OutputType.FILE);
And for where you save and name it ->
String fileName = “file.png”;
File DestFile = new File(“folder where you want to save\\” + fileName);
Files.copy(SrcFile, DestFile);
Headless Browser
A headless browser is a term used to define browser simulation programs that do not have a GUI. These programs execute like any other browser but do not display any UI. You can use HTMLUnitDriver for headless browsers.
WebDriver driver = new HtmlUnitDriver();
driver.get(“url”);