Selenium WebDriver




1. Verify if Back ground image is loaded or not


Some times it may happen that, you may not see any xpath for the image that loads at background. When you inspect the image , you may simple see in the page source that some methods are called which internally be referring to some CSS values. To solve such situation following piece of code might help you to check if background image is loaded or not


It contains css selctor as "html#login body" which has image source.
public static void ifbackgroundimageLoaded()

 {

    WebElement ele = driver.findElement(By.cssSelector("html#login body"));
     String[] actualUrl = ele.getCssValue("background-image").split("[\\(||\\)]");
     System.out.println(actualUrl[0]);
     System.out.println(actualUrl[1]);
     String getExactUrl[]=actualUrl[1].split("\"");
     System.out.println(getExactUrl[1]);
 }


2. How to handle cookies

Following is a link which helps you to handle cookies.
https://www.guru99.com/handling-cookies-selenium-webdriver.html

Note: I have not come across any such scenario in my working experience. So did not put any example to explain. will update this page once i come across any such sceario.







3. If you want to execute POST xml and retrieve the values from its response(normally Json response) following methods suffices your requirement.

Note:
Jars to download "commons-httpclient-3.1.0.jar"
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.InputStreamRequestEntity;
import org.apache.commons.httpclient.methods.PostMethod;

import org.apache.commons.io.FileUtils;

Let us say the post xml request on execution, gives the following jason

{"name":"rahul","record_id":"234561"}

following method returns recor_id

public static String  CreateTicket_XMLDataPost(String sxmlFileName, String sUrl){

        String jsonresponse=null;
        @SuppressWarnings("deprecation")
        PostMethod post = new PostMethod(sUrl);
   

        try {

         post.setRequestEntity(new InputStreamRequestEntity(
                    new FileInputStream(sxmlFileName)));
            post.setRequestHeader("Content-type",
                    "application/xml");
            HttpClient httpclient = new HttpClient();
            int result = httpclient.executeMethod(post);
            System.out.println("Response status code: " + result);       
            System.out.println("Response body: ");
            jsonresponse=post.getResponseBodyAsString();
            System.out.println(jsonresponse);
       
        }
        catch (Exception e) {
          e.printStackTrace();
        }
        finally {
         post.releaseConnection();
        }

        return jsonresponse.split("record_id")[1].trim().substring(2, 8);

    }


Usage:

SCK_CreateTicket_XMLDataPost(System.getProperty("user.dir")+"\\src\\objectRepository\\post.xml", "service_url");


4. Updating XML node values

import java.io.File;
import java.io.IOException;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

public static void XMLNodeValueReplace(String inputFile,String outputFile,String sfieldName,String sfieldValue) throws SAXException, IOException, ParserConfigurationException, XPathExpressionException, TransformerException
  {
  Document doc = DocumentBuilderFactory.newInstance()
        .newDocumentBuilder().parse(new InputSource(inputFile));

    // locate the node(s)
    XPath xpath = XPathFactory.newInstance().newXPath();
    NodeList nodes = (NodeList)xpath.evaluate
        ("//ticketFields/fieldName[text()='"+sfieldName+"']/following-sibling::fieldValue", doc, XPathConstants.NODESET);

    // make the change
    for (int idx = 0; idx < nodes.getLength(); idx++) {
      nodes.item(idx).setTextContent(sfieldValue);
    }

    // save the result
    Transformer xformer = TransformerFactory.newInstance().newTransformer();
    xformer.transform
        (new DOMSource(doc), new StreamResult(new File(outputFile)));
  }


Usage:
Replace(inputxmlFile,outputxmlFile,"categoryId","2222");


5. Below method allows you to send emails in Selenium webdriver


Note1: Libraries required: javamail-1.4.7, commons-email-1.5-bin
Note2: TIP: While using commons email to send Emails, it may throw you authentication error. To solve this, login with the gmail that you are using send email  and set on by clicking the below link

https://myaccount.google.com/lesssecureapps?pli=1

import org.apache.commons.mail.DefaultAuthenticator;
import org.apache.commons.mail.Email;
import org.apache.commons.mail.EmailAttachment;
import org.apache.commons.mail.MultiPartEmail;

import org.apache.commons.mail.SimpleEmail;


public static boolean senEmailwithAttachment(String HOST, int PORT,String suName,String spWord,String sFrom,String sFromname,String sTo,String sToname,String sSubject,String sMessage,String attachmentFile,String attachmentName,String attachmentDescription) {
        
        
        try {
       
        // Create the attachment
    EmailAttachment attachment = new EmailAttachment();
    attachment.setPath(attachmentFile);
    attachment.setDisposition(EmailAttachment.ATTACHMENT);
    attachment.setDescription(attachmentDescription);
    attachment.setName(attachmentName);
       
    //Email email = new SimpleEmail();
    MultiPartEmail email = new MultiPartEmail();
    email.setHostName(HOST);
    email.setSmtpPort(PORT);
    email.setAuthenticator(new DefaultAuthenticator(suName,spWord));
    email.setSSLOnConnect(true);
    email.setFrom(sFrom,sFromname);
    email.setSubject(sSubject);
    email.setMsg(sMessage);
    email.addTo(sTo,sToname);
   
    // add the attachment
    email.attach(attachment);
      
    // send the email
    email.send();
    System.out.println("Email has been sent with attachment");
    return true;
        }catch(Exception ex){
            System.out.println("Unable to send email");
            System.out.println(ex);
            return false;
        }

    }


Usage: senEmailwithAttachment("smtp.gmail.com",465,"fromtestmail@gmail.com","password","fromtestmail@gmail.com","Fromname","togmail@gmail.com","toname","subject: Automation results","Message: Please find the attached results","attachmentfilepath","attachmentname","attachmentdescrption");

6. Firefox Options

//log file handing
System.setProperty(FirefoxDriver.SystemProperty.BROWSER_LOGFILE,"null")
System.setProperty(FirefoxDriver.SystemProperty.BROWSER_LOGFILE,Path of log file)
FirefoxOptions options=new FirefoxOptions();
options.setBinary("path to exe")
options.setPageLoadStrategy(PageLoadStrategy.EAGER) 

//firefox.exe -p profilemanager
ProfilesIni allprof=new ProfilesIni();
FirefoxProfile prof=allprof.getProfile("prof1")

//disable notifications
prof.setPreference("dom.webnotifications.enabled",false)

//certificates
//example: https://192.163.254.17")
prof.setAcceptUntrustedCertificate(true);
prof.setAssumeUnUntrustedCertificateIssuer(false);

//proxy
prof.setPreference("network.proxy.type",1)
prof.setPreference("network.proxy.socks","23.34.56.78")
prof.setPreference("network.proxy.socks_port","23.34.56.78")

options.setProfile(prof)


WebDriver driver=new FirefoxDriver(options)


//Chrome options

//To redirect the logs
system.setProperty(chromeDriverService.CHROME_DRIVER_LOG_PROPERTY,"D:\Logfile.log")
//To disappear log from console
ystem.setProperty(chromeDriverService.CHROME_DRIVER_SILENT_OUTPUT_PROPERTY,"true")

//turn off the notificaitons
chormeoptions ops=new ChromeOptions();
ops.addArguments("--disable-notifications");
ops.addAruguments("disable-infobars");
ops.addArguments("--start-maximized")

//Proxy
ops.addArguments("--proxy-server=http://83.345.94.67:5678")

//Profiling
//chorme://version this is where you get profile location
ops.addArguments("user-data-dir=C:\\Users\\Raman\\AppData\\Local\\Google\\Chrome\\User Data\\")--dont give default path here

//No certificate management

//page load strategy same as in firefox

//Binary
ops.SetBinary("exe path of chrome")



IE
====

logs
====
system.SetProperty("InternetExplorerDriverService.IE_DRIVER_LOGLEVEL_PROPERTY,"INFO") //FATAL,ERROR
system.setProperty("InternetExplorerDriverService.IE_DRIVER_LOGFILE_PROPERTY,"path of logfile")
system.setProperty("InternetExplorerDriverService.IE_DRIVER_SILENT_PROPERTY,"true")

//pageload strategy not there in IE
//Proxy

DesiredCapabilities cap=new DesiredCapabilities();
//Certificates-wont work in newer versions 
cap.setAcceptInsecureCerts(true);
cap.setCapability(CapabilityType.ACCEPT_SSL_CERTS,true);

String proxy="45.56.67.89:1234"
Proxy prox=new Proxy();
prox.setAutodetect(false);
prox.setProxytype(prox.ProxyType.MANUAL)
prox.setSocksProxy(proxy)
cap.setCapability(CapabilityType.PROXY,prox)
options.merge(cap)

//Certificates
dirver.get("https://192.163.254.17/")
driver.get("javascript:document.getElementById('overridelink').click();");

//no profiling and notifications

//EDGE

//logs
system.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY,"null")

//pageloadstrategy
EdgeOptions options=new EdgeOptions();
options.setPageLoadStrategy("eager")

//no profiling, no notificatons,no proxies
//Certificates
driver.get("http://192.163.254.17:2083/")
driver.findElement(by.id("moreInformationDropdownSpan")).click();
dirver.findElement(by.id("invalidcert_continue")).click();

7. Basic Excel Read and write operations

Dependencies for apache poi 
======================
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.17</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.17</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.poi/ooxml-schemas -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>ooxml-schemas</artifactId>
<version>1.0</version>
</dependency>

<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-scratchpad -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-scratchpad</artifactId>
<version>3.17</version>
</dependency>

<!-- https://mvnrepository.com/artifact/org.apache.xmlbeans/xmlbeans -->
<dependency>
<groupId>org.apache.xmlbeans</groupId>
<artifactId>xmlbeans</artifactId>
<version>2.6.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-excelant -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-excelant</artifactId>
<version>3.17</version>
</dependency>


 Excel code
=========
package ExcelUtilities;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.DateFormat;

import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.xssf.usermodel.charts.XSSFDateAxis;

import com.gargoylesoftware.htmlunit.javascript.host.Iterator;

public class readXL {
public static XSSFWorkbook Excelworkbook;
public static XSSFSheet Excelworksheet;
public static XSSFCell Excelcell;
public static XSSFRow Excelrow;

public static void readxl(String filename) {
try {
FileInputStream fip = new FileInputStream(filename);
Excelworkbook = new XSSFWorkbook(fip);

} catch (Exception e) {
}

}

public static int getLastrow(String sheetname) {
try {
Excelworksheet = Excelworkbook.getSheet(sheetname);
int row = Excelworksheet.getLastRowNum();
return row;
} catch (Exception e) {
return -1;
}
}

public static String getCelldata(String sheetname, int rownum, int colnum) {
try {
Excelworksheet = Excelworkbook.getSheet(sheetname);
Excelcell = Excelworksheet.getRow(rownum).getCell(colnum - 1);
String cellval;

if (Excelcell.getCellType() == Excelcell.CELL_TYPE_STRING)
cellval = Excelcell.getStringCellValue();
else if (Excelcell.getCellType() == Excelcell.CELL_TYPE_NUMERIC)
cellval = String.valueOf(Excelcell.getNumericCellValue());
// System.out.println("hello");
else
cellval = null;

return cellval;

} catch (Exception e) {
return "";
}
}


public static void iterateallrowsofExcel(String sheetname) {
Excelworksheet = Excelworkbook.getSheet(sheetname);
int colno=0;
String cellval;
java.util.Iterator<Row> itr = Excelworksheet.iterator();
while (itr.hasNext()) {
Row row = itr.next();
java.util.Iterator<Cell> cellitr = row.cellIterator();

while (cellitr.hasNext())
{
Cell cell = cellitr.next();


if (cell.getCellType()==cell.CELL_TYPE_STRING)
cellval=row.getCell(colno).getStringCellValue();    
else if (cell.getCellType()==cell.CELL_TYPE_NUMERIC)
{
cellval=String.valueOf(row.getCell(colno).getNumericCellValue());
if (DateUtil.isCellDateFormatted(cell))
{
cellval=String.valueOf(row.getCell(colno).getDateCellValue());
    cellval=DateFormat.getDateInstance(DateFormat.SHORT).format(row.getCell(colno).getDateCellValue());
}

}
else
cellval=null;

System.out.print(cellval+"\t");
colno++;
}
colno=0;
System.out.println();
}

}

public static void setCelldata(String sheetname, String fname, String result, int RowNum, int ColNum)
throws Exception {
CellStyle style = Excelworkbook.createCellStyle();
try {
Excelworksheet = Excelworkbook.getSheet(sheetname);
Excelcell = Excelworksheet.getRow(RowNum).getCell(ColNum - 1);
if (Excelcell == null) {
Excelcell = Excelrow.createCell(ColNum - 1);
Excelcell.setCellValue(result);
Excelcell.setCellStyle(style);
} else {
Excelcell.setCellValue(result);
Excelcell.setCellStyle(style);
}
FileOutputStream fileout = new FileOutputStream(fname);
Excelworkbook.write(fileout);
fileout.flush();
fileout.close();

} catch (Exception e) {
throw e;
}
}

public static void main(String[] args) throws Exception {

String fileparent = System.getProperty("user.dir") + "\\src\\main\\java\\Data\\Data.xlsx";

readxl(fileparent);
// System.out.println("Data Before change is=" + getCelldata("Student", 1, 3));
// System.out.println("last row of the sheet=" + getLastrow("Student"));
// setCelldata("Student", fileparent + "\\data.xlsx", "10", 1, 3);
// System.out.println("Data After change is=" + getCelldata("Student", 1, 3));

iterateallrowsofExcel("Student");

}

}

Comments

Popular Posts