Selenium WebDriver

Questions asked from following key areas of WebDriver
  1. Frame, windows handling
  2. Locating mechanism
  3. Data driven - Usually from Excel or from Properties file
  4. Web Form Handling- Includes drop down, table and calendar handling
  5. Synchronization i.e. waits Explicit and implicit.


Quick links to visit:
1. Miscellaneous Questions and Answers
2. Different browser invocations
                                                                                           
Quick points to note here are:

Frame handling:

What is frame: It is an Inline Frame (iFrame). An HTML doc embedded in another HTML doc like an advertisement.


  1. driver.switchTo().frame("name");//name- id or name or the WebElement attribute from DOM
  2. driver.defaultContent(); //In order to return from frame to main window
  3. driver.switchTo().frame("ParentFrame").switchTo().frame("ChildFrame");// In order switch to child (nested) frame from parent frame. if the above doesn't work in any of your specific way, you can get back from parent frame to Main window and then switchTo child frame directly by using #2 and #1 respectivrly.

Points to be in mind:

1. Return Type of SwitchTo() is TargetLocator
2. To get all the frames from a page:
List<WebElement> list=driver.findElements(By.tagName("iFrame"));
//below gives the count of frames in a page
System.out.println(list.size());
We can traverse through above list in order to work on the required frame of the page if we have so many in the page.
3. To get the frame name:
System.out.println(driver.findElement("name").getText());
4.NoSuchFrameException is shown when there is no mentioned frame found in DOM


Window handling: (It is a browser window/tab but not the native desktop windows)
One can work with windows/tabs by using their handles and can be captured by getWindowHandle() and getWindowHandles() commands.

When you'll be seeing this kind of handling: One have to click on link on one page and results in opening of another tab or browser window.

  1. driver.swtichTo().window("windowName or windowHandle");
  2. String SingleWindowHandle=driver.getWindowHandle(); //Which returns the handle of the window that driver working on
  3. Set<String> handles=driver.getWindowHandles();//To get all opened window Handles

Points to be in mind:
1. Return type of window handle is String and the Set<String> is the return type of getWindowHandles

Locating Mechanism: 


Attribute Xpath CSS
id //input[@id='email']  input#email
name //input[@name='user']    input[name=user] or  input[name='user']
//input[@type='type_name' and/or @name='user'] input[type=type_name and/or name='user']
class //input[@class='class_name'] input.class_name
if the element is like: <div class='log cat'></div> //div[@class='log cat'] div.log.cat
search as per the text that node contains //div[contains(text(),'text')] or //div[contains(.,'text')] input[value^='Goo'] - Start of String or input[value$='rch'] - End of String  or input[value*='Sea'] - Contains of String 
                          
preceding-sibling::element - Selects preceded siblings of context node
preceding::element - Element selects all nodes which are represented before the context node
following-sibling::element - Element selects following siblings under this node
following::element - 
Element selects all nodes which are represented after the context node
parent::* or xpath/.. - Represents the parent node of selected node - This will be empty when context node and & root node are same
child::* - First most element of the list (or)
child::input[position()>0] - first most element of the list
                                   >1  - 2nd element
                                   >2  - 3rd element

Note:Above preceding and following methods also go with * like preceding-sibling::* results in first most element in preceded siblings of context node.

Child elements:
XPath - //input/a  ----------- CSS - input>a

Adjacent tags:
Xpath - Can use above preceding/followin/parent --- CSS - input[value*='search']+input[1]

Selecting nth tag from list:
Xpath - //input/a[5] ------------ CSS - nth-of-type(5) or nth-child(5)


Points to be in mind:

1. Most preferable way to locate elements can be id - name - cssSelector - xpath
2. id,name,cssSelector are mostly used while working with IE browser
3. DOM - Document Object Modal which treats everything (HTML or XML) as tree structure where each node represents a part of document

Data driven development:
It is basically to separate test data with test scripts to avoid hard coding and can be performed using:

1. Excel
2. Properties file


Reading from Excel:

package WorkingWithExcel;
import java.io.File;
import java.io.FileInputStream;
import java.util.Iterator;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ReadingAnExcelFile {
@SuppressWarnings("deprecation")
public static void main(String a[]) {
try {
FileInputStream file = new FileInputStream(new File(
"D:\\Yes\\selenium\\howtodoinjavaxlx.xlsx"));
// hold the reference of the .xlsx file
XSSFWorkbook workbook = new XSSFWorkbook(file);
// Get the desired sheet from book
XSSFSheet sheet = workbook.getSheetAt(0);
// Iterate through each row in sheet
Iterator<Row> rowIterator = sheet.iterator();
while (rowIterator.hasNext()) {
Row row = rowIterator.next();
// for each row iterate through all the columns
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
switch (cell.getCellType()) {
case Cell.CELL_TYPE_NUMERIC:
                        System.out.print(cell.getNumericCellValue() + "\t");
                        break;
                    case Cell.CELL_TYPE_STRING:
                        System.out.print(cell.getStringCellValue() + "\t");
                        break;
}
}
System.out.println("");
}
file.close();

} catch (Exception e) {
System.out.println(e);
}
}

}

Writing into Excel file:

package WorkingWithExcel;
import java.io.File;
import java.io.FileOutputStream;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class WriteInExcel {
public static void main(String a[]) {
// Create a blank workbook
XSSFWorkbook workbook = new XSSFWorkbook();
// Create a blank sheet
XSSFSheet sheet = workbook.createSheet("Employee Data");
// This data needs to be written
Map<String, Object[]> data = new TreeMap<String, Object[]>();
data.put("1", new Object[] { "ID", "NAME", "LASTNAME" });
data.put("2", new Object[] { 1, "Amit", "Shukla" });
data.put("3", new Object[] { 2, "Lokesh", "Gupta" });
data.put("4", new Object[] { 3, "John", "Adwards" });
data.put("5", new Object[] { 4, "Brian", "Schultz" });
// Iterate over data and write it to sheet
Set<String> keyset = data.keySet();
int rownum = 0;
for (String key : keyset) {
Row row = sheet.createRow(rownum++);
Object[] objArry = data.get(key);
int cellnum = 0;
for (Object obj : objArry) {
Cell cell = row.createCell(cellnum++);
if (obj instanceof String)
cell.setCellValue((String) obj);
else if (obj instanceof Integer)
cell.setCellValue((Integer) obj);
}
}
try {
// Write the workbook in file system
FileOutputStream FOS = new FileOutputStream(new File("D:\\Yes\\selenium\\howtodoinjavaxlx.xlsx"));
workbook.write(FOS);
FOS.close();
System.out.println("Writing completed!!");
} catch (Exception e) {
e.printStackTrace();
}
}
}

Reading from properties file:

1. Write the data in the form of key-value pairs in a file and save that with '.properties' extension
2. Write below code to read it:

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;

import java.util.Set;
public class PropertiesAllOperations {

public static void main(String[] args) throws FileNotFoundException,
IOException {
FileInputStream fis = new FileInputStream(new File(
"D:/ADT/AND/And1/Java/src/myfile.properties"));
//Instantiate properties class
Properties p = new Properties();
//Load the file

p.load(fis);
System.out.println(p.getProperty("key1","its default value"));//we can explicitly define the default value
System.out.println(p.getProperty("key2"));
System.out.println(p.getProperty("key3"));
}

}

Writing into properties file: 

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Properties;

public class WritingIntoProperties {
public static void main(String[] args) throws
IOException {
Properties prop = new Properties();
//Creating file at the mentioned location
OutputStream output = new FileOutputStream("D:/Yes/config.properties");
// set the properties value
prop.setProperty("Key1", "Value1");
prop.setProperty("Key2", "Value2");
prop.setProperty("Key3", "Value3");
// save properties to project root folder
prop.store(output, null);
}

}
Go and open the file in mentioned location and observe that keys with values are displayed with the time stamp.


No comments:

Post a Comment