In this blog we will learn some common Selenium features which we will be using in most our project. These features will be widely used in project.
Launching a browser with all settings for the browser
WebDriverManager.chromedriver().setup();
WebDriverManager.chromedriver().clearDriverCache();
WebDriverManager.chromedriver().clearResolutionCache();
//WebDriverManager.chromedriver().browserVersion("110.0.0").setup();
ChromeOptions chromeOptions = new ChromeOptions(); chromeOptions.setPageLoadStrategy(PageLoadStrategy.NORMAL);
chromeOptions.setAcceptInsecureCerts(true);
chromeOptions.setScriptTimeout(Duration.ofSeconds(30));
chromeOptions.setPageLoadTimeout(Duration.ofMillis(30000)); chromeOptions.setImplicitWaitTimeout(Duration.ofSeconds(20));
chromeOptions.addArguments("--remote-allow-origins=*");
driver=new ChromeDriver(chromeOptions);
driver.get("https://westbengal.covidsafe.in/");
driver.manage().window().maximize();
Counting number of rows and columns in a table
Row = tr
List<WebElement> rows=driver.findElements(By.tagName("tr"));
int noOfRows=rows.size();
System.out.println("no of rows :" +noOfRows );
Column= th
List<WebElement> columms=driver.findElements(By.tagName("th"));
int noOfColumns=columms.size();
System.out.println("no of columns :" +noOfColumns );
Sample Code to find number of Rows and Columns
"https://westbengal.covidsafe.in/"
// ************** FINDING NO OF ROWS ****************************************
//List<WebElement> hospitals=driver.findElements(By.xpath("//strong[contains(text(),'Hospital')]"));
List<WebElement> rows=driver.findElements(By.xpath("//tbody/tr"));
//List<WebElement> rows=driver.findElements(By.xpath("//tr"));
int rows_count=rows.size();
System.out.println("No Of Hospitals rows :" + rows_count);
// ************* FINDING NO OF COLUMNS ***************************************
List<WebElement> columns=driver.findElements(By.xpath("//tr[1]//td"));
int column_count=columns.size();
System.out.println("No Of Hospitals columns:" + column_count);
To get the data and print the text written in first row first column of a table
"https://westbengal.covidsafe.in/"
// FINDING THE NAME OF THE HOSPITAL IN FIRST ROW FIRST COLUMN [1][1] ********************************************
WebElement firstHospital=driver.findElement(By.xpath("//tr[1]//strong"));
String hospitalNmae=firstHospital.getText();
System.out.println(" first hospital name:" + hospitalNmae);
System.out.println();
String hospitalName=firstHospital.getText();
System.out.println(" first hospital name:" + hospitalName);
Getting and Printing data in first column in a table
"https://westbengal.covidsafe.in/"
//************** FINDING THE ALL HOSPITAL NAMES IN FIRST COLUMN *********************
for(int i=1;i<=rows_count;i++)
{
WebElement eachHospital=driver.findElement(By.xpath("//tr["+i+"]//strong"));
String hospitalName1=eachHospital.getText();
System.out.println("Names of the Hospital : " +hospitalName1);
}
Getting data from each row and each column from a table
"https://westbengal.covidsafe.in/"
// GETTING DETAILS OF EACH HOSPITAL finding all rows and column values ************************************************
for(int i=1;i<=rows_count;i++)
{
for(int j=1;j<=column_count;j++)
{
WebElement eachHospitalDetails=driver.findElement(By.xpath("//tr["+i+"]/td["+j+"]"));
String hospitalDetails=eachHospitalDetails.getText();
System.out.println();
System.out.println(hospitalDetails );
}
}
Moving cursor from top to down to some extent
Using Scroll
JavascriptExecutor jse= (JavascriptExecutor) driver;
jse.executeScript("scroll(0, 3050)");
Using ScrollIntoView
JavascriptExecutor jse = (JavascriptExecutor)driver;
WebElement table=driver.findElement(By.xpath("//div[@role='rowgroup']"));
jse.executeScript("arguments[0].scrollIntoView()", table);
To Click a particular element
JavascriptExecutor jse = (JavascriptExecutor)driver;
js.executeScript("arguments[0].click()", hosp_name);
How to take Single Screenshot
TakesScreenshot screenshot3 =( TakesScreenshot) driver;
File sourceFile3=screenshot3.getScreenshotAs(OutputType.FILE);
File destinationFile3 = new File("C://Users//Reka//eclipse-workspace//Reka_Selenium_NN//src//test//java//Selenium//sample.png");
//FileUtils.copyFile(sourceFile3, destinationFile3);
FileHandler.copy(sourceFile3, destinationFile3);
How to have multiple Screenshot
public void CollectionscreenShot(String fileName) throws IOException {
TakesScreenshot screenshot =( TakesScreenshot) driver;
File sourceFile=screenshot.getScreenshotAs(OutputType.FILE);
File destinationFile = new File("C:\\Users\\Reka\\git\\DS-ALGO-94NN\\screenshot\\"+fileName);
FileHandler.copy(sourceFile, destinationFile);
}
Calling the screenshot method
collection.CollectionscreenShot("Sample1.png");
To Clear the text in input box and then send input
//driver.findElement(city).clear();
driver.findElement(city).sendKeys(Keys.CONTROL + "A");
driver.findElement(city).sendKeys(Keys.CONTROL + "X");
driver.findElement(city).sendKeys("chennai");
To select an element from DropDown
selectByVisibleText (" string ")
selectByIndex(int )
selectByValue(" " )
//selecting multiple values from dropdown
WebElement dropArrow=driver.findElement(By.id("j_idt87:auto-complete_input"));
Select fromdrop=new Select(dropArrow);
fromdrop.selectByIndex(2);
fromdrop.selectByValue("4");
fromdrop.selectByVisibleText("PostMan");
fromdrop.selectByVisibleText("Appium");
Accept a ALERT
"http://testleaf.herokuapp.com/pages/Alert.html"
WebElement okalert=driver.findElement(By.xpath("//*[@id=\"contentblock\"]/section/div[1]/div/div/button"));
okalert.click();
Alert alertwindow=driver.switchTo().alert();
//Thread.sleep(3000);
alertwindow.accept();
Dismiss a ALERT
"http://testleaf.herokuapp.com/pages/Alert.html"
WebElement confirmBox=driver.findElement(By.xpath("//*[@id=\'contentblock\']/section/div[2]/div/div/button"));
confirmBox.click();
Alert alertwindow1=driver.switchTo().alert();
alertwindow1.dismiss();
PromptBox send text and accept
"http://testleaf.herokuapp.com/pages/Alert.html"
WebElement promptBox=driver.findElement(By.xpath("//*[@id=\'contentblock\']/section/div[3]/div/div/button"));
promptBox.click();
Alert alertwindow2=driver.switchTo().alert();
alertwindow2.sendKeys("selenium");
alertwindow2.accept();
Drag and Drop using Actions
"https://testautomationpractice.blogspot.com/"
WebElement sourceDrag=driver.findElement(By.xpath("//*[@id=\'draggable\']/p")) ;
WebElement targetDrop=driver.findElement(By.xpath("//div[@id='droppable']"));
Actions actions=new Actions(driver);
actions.clickAndHold(sourceDrag).moveToElement(targetDrop).release(targetDrop).build().perform();
To list number of options
"https://www.leafground.com/select.xhtml"
List<WebElement> listOfOption=selectfrom.getOptions();
int sizeoflist= listOfOption.size();
System.out.println(sizeoflist);
Total number of Links with tagname "a"
List<WebElement> totalLinks= driver.findElements(By.tagName("a"));
int noOfLinks=totalLinks.size();
System.out.println(noOfLinks);
Windows Handling
It is a unique identifier that holds the address of all the windows. Think of it as a pointer to a window, which returns the string value. It is assumed that each browser will have a unique window handle.
getWindowHandle() returns the window handle of currently focused window/tab.
Return type of getWindowHandle() is String
String parentWindow=driver.getWindowHandle();
System.out.println("Parent window: "+parentWindow);
Parent window: 606B3572AF4640B4B85508F22A9E6B76
getWindowHandles() returns all windows/tabs handles launched/opened by same driver instance including all parent and child window.
Return type of getWindowHandles() is Set<String>
switchTo(): Using this method, we can perform switch operations within windows.
When you click a Link , you don't know how many windows will open , so put loop and to get all window id's and move to new window
Set<String> windows=driver.getWindowHandles();
for (String windowid : windows)
{
//to move to newly opened window
driver.switchTo().window(windowid);
}
Navigate back to Main Page
driver.switchTo().window(parentWindow);
If child window is not equal to parent window, close child window if parent window is equal to parent window then exit loop
for (String windowidno : windows)
{
if (!windowidno.equals(parentWindow))
{
driver.switchTo().window(windowidno);
driver.close();
}
}
Selenium Waits
In automation testing, wait commands direct test execution to pause for a certain length of time before moving onto the next step. This enables WebDriver to check if one or more web elements are present/visible/enriched/clickable, etc.
What are the three types of wait in Selenium?
Implicit, Explicit and Fluent Wait are the different waits used in Selenium. Usage of these waits are totally based on the elements which are loaded at different intervals of time. It is always not recommended to use Thread.Sleep() while Testing our application or building our framework.
Implicit wait
Implicit wait stays in place for the entire duration for which the browser is open. The default value of implicit wait is 0. Implicit wait is applied for the lifetime of the Webdriver, it can extend the test execution times to a large value depending on the number of elements on which it is being called.
An implicit wait is to tell WebDriver to poll the DOM for a certain amount of time when trying to find an element or elements if they are not immediately available. The default setting is 0, meaning disabled
The main function of implicit Wait is to tell the web driver to wait for some time before throwing a "No Such Element Exception". Its default setting is knocked at zero. Once the time is set, the driver automatically will wait for the amount of time defined by you before throwing the above-given exception.
driver.manage().timeouts().implicitlyWait(TimeOut, TimeUnit.SECONDS);
Explicit Wait
Explicit Waits also known as Dynamic Waits because it is highly specific conditioned. It is implemented by WebDriverWait class. To understand why you need Explicit Wait in Selenium, you must go through the basic knowledge of the wait statements in a program. In simple terms, you must know some conditions.
In the syntax, create an object of WebDriver wait and passed driver reference and timeout as parameters.
WebDriverWait wait=new WebDriverWait(WebDriveReference,TimeOut);
Fluent Wait
Fluent Wait is quite similar to explicit Wait. It is similar in terms of management and functioning. In Fluent Wait, you can perform wait for action for an element only when you are unaware of the time it might take to be clickable or visible. Few differential factors that Fluent offers are as follows:
The pooling frequency
The pooling frequency in the case of Explicit is 500 milliseconds. But, using Fluent Wait, this pooling frequency can be changed to any value based upon your need. This usually means telling the script to keep an eye on the element after every 'x' seconds.
Ignore Exception
While pooling, if an element is not found, you can ignore some expectations like 'NoSuchElement'. Apart from this factor, similar to Explicit and Implicit Wait, you can define the amount of time for the element to be actionable or visible.
Syntax:
Wait<WebDriver> fluentWait = new FluentWait<WebDriver>(driver)
.withTimeout(60, SECONDS) // this defines the total amount of
time to wait for
.pollingEvery(2, SECONDS) // this defines the polling frequency
.ignoring(NoSuchElementException.class); // this defines the
exception to ignore
WebElement elemnent = fluentWait.until(new Function<WebDriver,
WebElement>()
{
public WebElement apply(WebDriver driver) //in this method
defined your own subjected conditions for which we need to wait for
{ return driver.findElement(By.id("element"));
}});
Conclusion:
I hope, This article will help you to understand Selenium features which will be used mostly for every project. This blog will be handy to refer features and use in our project,
You must have got an idea on the topics explained in this blog. Lets explore more and learn New Topics.
Happy Learning
Comments