Taking a screen shot using Selenium - java

I imported this class from another package and try to call this method, but it is not working.
When I created this method in the same class and called it, it is working.
private void getScreenshot() throws IOException
{
File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
SimpleDateFormat dateFormat = new SimpleDateFormat("DD-MM-YYYY/hh-mm-ssaa");
String destfile = dateFormat.format(new Date()) + ".png";
FileUtils.copyFile(scrFile, new File("D:\\workspace\\Firewall\\Resources\\ScreenShots\\"+destfile));
}

I guess the main reason is that you import wrong libraries. Check out:
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.junit.Test;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
And in case, if your libraries will be the same, try to use my method:
public class TakeScreenshot {
WebDriver driver;
public TakeScreenshot(WebDriver driver){
this.driver = driver;
}
public void ScreenShot(String nameTc)
{
// Take screenshot and store as a file format
File src= ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
try {
// now copy the screenshot to desired location using copyFile //method
FileUtils.copyFile(src, new File("bin/" + nameTc + ".png"));
}
catch (IOException e)
{
System.out.println(e.getMessage());
}} }

By using this you can capture screenshot, just need to call captureScreenShot() method for taking screenshot by sending file path
public static void captureScreenShot(String filePath)
{
File scrFile =((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
try
{
FileUtils.copyFile(scrFile, new File(filePath)); }
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace(); }}

Related

Java scripting in Katalon-Studio

I have several java tests that I wrote and used to run them with Eclipse.
I want to import them to katalon and run them.
For example, I have a login script here:
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.*;
public class Login {
public static void main(String args[]) throws IOException {
IOException ioe = new IOException();
//Initializing server
System.setProperty("webdriver.chrome.driver", "C:/selenium/chromedriver.exe");
ChromeDriver wd = new ChromeDriver();
wd.manage().window().maximize();
wd.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
//login
System.out.println("*** login ***");
wd.get("<URL>");
wd.findElement(By.xpath("//form[#id='form']/div[1]/paper-input/paper-input-container/div[2]/div/input")).click();
wd.findElement(By.xpath("//form[#id='form']/div[1]/paper-input/paper-input-container/div[2]/div/input")).clear();
wd.findElement(By.xpath("//form[#id='form']/div[1]/paper-input/paper-input-container/div[2]/div/input")).sendKeys("<USERNAME>");
wd.findElement(By.xpath("//form[#id='form']/div[2]/paper-input/paper-input-container/div[2]/div/input")).click();
wd.findElement(By.xpath("//form[#id='form']/div[2]/paper-input/paper-input-container/div[2]/div/input")).clear();
wd.findElement(By.xpath("//form[#id='form']/div[2]/paper-input/paper-input-container/div[2]/div/input")).sendKeys("<PASSWORD>");
wd.findElement(By.xpath("//form[#id='form']//paper-button[.='login']")).click();
try { Thread.sleep(3000l); } catch (Exception e) { throw new RuntimeException(e); }
if(wd.findElement(By.tagName("html")).getText().contains("please login")){
System.out.println("Login failed");
throw ioe;
}//End of login
System.out.println("Login was executed successfully!");
System.out.println("Testcase finished successfully!");
wd.quit();
}
}
I want to run it as is in katalon but I'm not sure how.
Thanks.
I try adding the existing java script without declaring class and main method and it work.
In your example, please remove: import org.openqa.selenium.*; , replace it with: import org.openqa.selenium.By then paste the remain script without
public class Login {
public static void main(String args[]) throws IOException {
}}
So your custom test case in Katalon would be:
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.By;
IOException ioe = new IOException();
//Initializing server
System.setProperty("webdriver.chrome.driver", "C:/selenium/chromedriver.exe");
ChromeDriver wd = new ChromeDriver();
wd.manage().window().maximize();
wd.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
//login
System.out.println("*** login ***");
wd.get("<URL>");
wd.findElement(By.xpath("//form[#id='form']/div[1]/paper-input/paper-input-container/div[2]/div/input")).click();
wd.findElement(By.xpath("//form[#id='form']/div[1]/paper-input/paper-input-container/div[2]/div/input")).clear();
wd.findElement(By.xpath("//form[#id='form']/div[1]/paper-input/paper-input-container/div[2]/div/input")).sendKeys("<USERNAME>");
wd.findElement(By.xpath("//form[#id='form']/div[2]/paper-input/paper-input-container/div[2]/div/input")).click();
wd.findElement(By.xpath("//form[#id='form']/div[2]/paper-input/paper-input-container/div[2]/div/input")).clear();
wd.findElement(By.xpath("//form[#id='form']/div[2]/paper-input/paper-input-container/div[2]/div/input")).sendKeys("<PASSWORD>");
wd.findElement(By.xpath("//form[#id='form']//paper-button[.='login']")).click();
try { Thread.sleep(3000l); } catch (Exception e) { throw new RuntimeException(e); }
if(wd.findElement(By.tagName("html")).getText().contains("please login")){
System.out.println("Login failed");
throw ioe;
}//End of login
System.out.println("Login was executed successfully!");
System.out.println("Testcase finished successfully!");
wd.quit();

How to upload Multiple files in selenium?

I'm trying to use following code :-
driver.findElement(By.xpath(".//*[#id='attach0']")).sendKeys("first path"+"\n"+"second path""+"\n"third path");
I didn't get result.
you can use AutoIT or JAVA code. Below i have used both for your reference. Try anyone of them
import java.io.IOException;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class AutoITforUpload {
private static WebDriver driver;
private static WebDriverWait waitForElement;
#FindBy(css = "span.btn.btn-success.fileinput-button")
private WebElement Add_files_btn;
#BeforeClass
public static void setUp() {
DesiredCapabilities desicap = new DesiredCapabilities();
System.setProperty("webdriver.chrome.driver", "D:/WorkSpace/Driver/chromedriver.exe");
desicap = DesiredCapabilities.chrome();
driver = new ChromeDriver(desicap);
driver.manage().window().maximize();
driver.get("https://blueimp.github.io/jQuery-File-Upload/");
waitForElement = new WebDriverWait(driver, 30);
}
#Test
public void AutoitUpload() {
// String filepath =
// "D:/Mine/GitHub/BasicProgramLearn/AutoItScript/unnamed.png";
WebElement btn = driver.findElement(By.cssSelector("span.btn.btn-success.fileinput-button"));
String file_dir = System.getProperty("user.dir");
String cmd = file_dir + "\\AutoItScript\\unnamed.png";
System.out.println("File directory is " + file_dir);
try {
// Using ordinary
Thread.sleep(3000);
for(int i=0;i<3;i++) //multiple times upload ;
driver.findElement(By.xpath("//*[#id='fileupload']/div/div[1]/span[1]/input")).sendKeys(cmd);
//use any String Array for multiple files
waitForElement(btn);
btn.click();
Thread.sleep(3000);
System.out.println(file_dir + "/AutoItScript/FileUploadCode.exe");
Runtime.getRuntime().exec(file_dir + "\\AutoItScript\\ChromeFileUpload.exe" + " " + cmd);
} catch (InterruptedException | IOException e) {
e.printStackTrace();
}
}
#AfterClass
public static void TearDown() {
try {
Thread.sleep(5000);
driver.quit();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private void waitForElement(WebElement vElement) {
waitForElement.until(ExpectedConditions.visibilityOf(vElement));
}
}
The code in AutoIt is
#include<IE.au3>
If $CmdLine[0] < 2 Then
$window_name="Open"
WinWait($window_name)
ControlFocus($window_name,"","Edit1")
ControlSetText($window_name,"","Edit1",$CmdLine[1])
ControlClick($window_name,"","Button1")
EndIf
Hope this gives you an idea

How to read data from excel file one line at a time

i want my program to read a single line (which will contain a URL) from excel file. Go to that URL and read next line -->go to the URL untill entire file is read.
import java.io.*;
import java.util.concurrent.TimeUnit;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
public class readDataFromExcelFile{
public static void main(String[] args) {
WebDriver driver = new FirefoxDriver();
driver.get("http://www.google.com");
driver.manage().window().maximize();
WebElement searchbox = driver.findElement(By.name("q"));
try {
FileInputStream file = new FileInputStream(new File("E://TestData.xlsx"));
XSSFWorkbook workbook = new XSSFWorkbook(file);
XSSFSheet sheet = workbook.getSheetAt(0);
for (int i=1; i <= sheet.getLastRowNum(); i++){
String keyword = sheet.getRow(i).getCell(0).getStringCellValue();
searchbox.sendKeys(keyword);
searchbox.submit();
driver.manage().timeouts().implicitlyWait(10000, TimeUnit.MILLISECONDS);
}
file.close();
} catch (FileNotFoundException fnfe) {
fnfe.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
But the above program will get all the /urls at a single time. Can you please tell me what should i modify in the code.
Clear the field before typing more text into it.
sendKeys() does just what it says: It sends a series of "user pressed key X" to the browser. So if the field already contains content, then the new keys are appended.
See: Clear text from textarea with selenium

Writing in a text File in java

I wrote a very simple piece of code, It was working perfectly since yesterday but now not working and even after lots of research/debugging i have not got the issue
import java.net.InetAddress;
import java.util.Date;
import java.io.File;
import java.io.FileWriter;
import java.io.BufferedWriter;
public class DetectLoggedInUser{
public static void returnUserName()
{
String computerName;
try {
File file =new File("d:\\TestFolder\\UsersloggedIn.txt");
if(!file.exists()){
file.createNewFile();
}
FileWriter fileWritter = new FileWriter(file.getName(),true);
BufferedWriter bufferWritter = new BufferedWriter(fileWritter);
String content= "\n UserName="+System.getProperty("user.name")+ " || Date and Time= "+new Date();
bufferWritter.write(content);
bufferWritter.close();
}
catch(Exception ex) {
ex.printStackTrace();
}
}
public static void main(String args[])
{
returnUserName();
}
}
Now file is created but nothing is being written in file
Is there anything wrong with this code(keeping in mind it was working since yesterday)?
Try this:
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.util.Date;
public class DetectLoggedInUser {
public static void returnUserName() {
try {
File file = new File("d:\\TestFolder\\UsersloggedIn.txt");
if (!file.exists()) {
file.createNewFile();
}
FileWriter fileWritter = new FileWriter(file, true);
BufferedWriter bufferWritter = new BufferedWriter(fileWritter);
String content = "\n UserName=" + System.getProperty("user.name")
+ " || Date and Time= " + new Date();
bufferWritter.write(content);
bufferWritter.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
public static void main(String args[]) {
returnUserName();
}
}
You can use
FileWriter fileWritter = new FileWriter(file.getAbsolutePath(), true);
Instead of file.getName() in your code.File.getName() method returns only the name of the file or directory,not the absolute path;
You don't need to check if the files exists or not, beside that it works fine for me.

How to render PNG image from DFX file by using kabeja package?

I'm new to this kabeja package so please can some one provide code example or reading material to render PNG from DXF file using Java?
This is the sample code that generate PNG image from DXF file.
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.HashMap;
import org.kabeja.dxf.DXFDocument;
import org.kabeja.parser.*;
import org.kabeja.parser.ParserBuilder;
import org.kabeja.svg.SVGGenerator;
import org.kabeja.xml.*;
public class MyClass {
public static void main(String[] args) {
MyClas x=new MyClas();
x.parseFile("C:\\Users\\Space\\Desktop\\test2.dxf");
}
public void parseFile(String sourceFile) {
try {
FileOutputStream o=new FileOutputStream("C:\\Users\\Space\\Desktop\\test2.png");
InputStream in = new FileInputStream(sourceFile);//your stream from upload or somewhere
Parser dxfParser = ParserBuilder.createDefaultParser();
dxfParser.parse(in, "");
DXFDocument doc = dxfParser.getDocument();
SVGGenerator generator = new SVGGenerator();
//org.xml.sax.InputSource out = SAXPNGSerializer;
SAXSerializer out = new org.kabeja.batik.tools.SAXPNGSerializer();
out.setOutput(o);
generator.generate(doc,out,new HashMap());
} catch (ParseException e) {
e.printStackTrace();
} catch (Exception ioe) {
ioe.printStackTrace();
}
}
}
Hope you get what you required :)

Categories