How to open links consecutelively from CSV - java

I'm trying to open links one-by-one from a CSV-file.
So far I've only managed to launch Chrome. How do you add the data source to the code? After that you should be able to simply open every link as loop.
Thank you!
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class LaunchChrome {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "D:\\user\\chromedriver_win32\\chromedriver.exe");
WebDriver driver=new ChromeDriver();
driver.get("URL from CSV as Loop");
}
}

Please check below piece of code and lets know if it resolved your problem
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class LaunchChrome {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "D:\\user\\chromedriver_win32\\chromedriver.exe");
WebDriver driver=new ChromeDriver();
readFileLineByLineUsingBufferedReader(driver);
}
public static void readFileLineByLineUsingBufferedReader(WebDriver driver) {
BufferedReader reader;
try {
reader = new BufferedReader(new FileReader("CSV_FILE_PATH"));
String line = reader.readLine();
while(line != null) {
driver.get(line);
// You may give some pause here (Thread.sleep(2000));
// read next line
line = reader.readLine();
}
reader.close();
} catch(IOException io) {
io.printStackTrace();
}catch(Exception e) {
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 handle popups on website

title : handle popup box
selenium code for handle div pop on same windows
//package booking;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class Dubai {
public static void main(String[] args) throws Exception {
System.setProperty ("webdriver.chrome.driver",
"C:\\Users\\miyau\\Desktop\\test\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("http://www.thomascook.in/");
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.findElement(By.xpath("//div[text()='Not Now']")).click();
System.out.println("operation complit");
}
}
// snapshot of popup## Heading ##
You can try this code:
public class Dubai {
public static void main(String[] args) throws InterruptedException {
try {
public static void main(String[] args) throws Exception {
System.setProperty ("webdriver.chrome.driver",
"C:\\Users\\miyau\\Desktop\\test\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
WebDriverWait wait=new WebDriverWait(driver,50 );
driver.manage().window().maximize();
Thread.sleep(500);
driver.get("http://www.thomascook.in/");
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.switchTo().frame(driver.findElement(By.xpath("//iframe[#class='__st_preview_frame_bpn']")));
System.out.println(driver.findElement(By.xpath("html/body/div[1]/div[2]/div[3]/span")).getText());
driver.findElement(By.id("__st_bpn_no")).click();
} catch (Exception e) {
e.printStackTrace();
}
}
}

Taking a screen shot using Selenium

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(); }}

How to Upload a file into web browser using Winium?

I know I can upload file to browser with many ways such as: AutoIt, Robot Class, and other ways(I tried them all and they worked most of time).
I got introduced to Winium and I would like to make the same test case with it, that is, upload a file to a browser using it, but I did not know what to do to switch between web driver to winium driver. Please help because I searched a lot for this trick but could not find any result
package testUtilities;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.winium.WiniumDriver;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
public class WiniumWeb
{
WebDriver driver;
#BeforeClass
public void setUp() throws IOException
{
driver = new FirefoxDriver();
driver.navigate().to("http://the-internet.herokuapp.com/upload");
driver.findElement(By.id("file-upload")).click();
String WiniumEXEpath = System.getProperty("user.dir") + "\\Resources\\Winium.Desktop.Driver.exe";
File file = new File(WiniumEXEpath);
if (! file.exists())
{
throw new IllegalArgumentException("The file " + WiniumEXEpath + " does not exist");
}
Runtime.getRuntime().exec(file.getAbsolutePath());
try
{
driver = new WiniumDriver(new URL("http://localhost:9999"), null);
} catch (MalformedURLException e)
{
e.printStackTrace();
}
}
#Test
public void testNotePade() throws InterruptedException
{
String file = System.getProperty("user.dir") + "\\Resources\\TestData.csv";
WebElement window = driver.findElement(By.className("File Upload"));
window.findElement(By.className("#32770")).sendKeys(file);
Thread.sleep(2000);
}
}
if you are still finding solution.I am sharing my script which worked for me.
public class FileUpload extends BaseClass {
static WiniumDriver d;
#BeforeClass
public void setUp() throws IOException {
DesktopOptions options = new DesktopOptions();
options.setApplicationPath("C:\\Windows\\System32\\openfiles.exe");
LaunchLocalBrowser("chrome","http://the-internet.herokuapp.com/upload");//use your own code to launch browser
driver.findElement(By.id("file-upload")).click();
String WiniumEXEpath = System.getProperty("user.dir") + "\\lib\\Winium.Desktop.Driver.exe";
File file = new File(WiniumEXEpath);
if (! file.exists()) {
throw new IllegalArgumentException("The file " + WiniumEXEpath + " does not exist");
}
Runtime.getRuntime().exec(file.getAbsolutePath());
try {
d = new WiniumDriver(new URL("http://localhost:9999"),options);
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
#Test
public void testNotePade() throws InterruptedException {
String file = System.getProperty("user.dir") + "\\lib\\Testdata.txt";
d.findElementByName("File name:").sendKeys(file);
d.findElementByXPath("//*[#Name='Cancel']//preceding-sibling::*[#Name='Open']").click();
driver.findElement(By.id("file-submit")).click();
}
}
File upload using WiniumDriverService by referring to port- 9999. Creating winium instance using free port having issues. Below code is intended for sample implementation of Browser factory to facilitate web and desktop instances.
public class FactoryManager {
public static ClientFactory getIndividualProduct(EnumProductLists product) {
ClientFactory factory = null;
if (null != product) {
switch (product) {
case CHROME:
factory = new ProductChromeClient();
break;
case DESKTOP:
factory = new ProductWiniumClient();
break;
default:
break;
}
}
return factory;
}
}
import java.io.File;
import java.io.IOException;
import org.openqa.selenium.winium.DesktopOptions;
import org.openqa.selenium.winium.WiniumDriver;
import org.openqa.selenium.winium.WiniumDriverService;
public class ProductWiniumClient extends ClientFactory {
private WiniumDriverService service;
#Override
protected void startService() {
if (null == service) {
service = new WiniumDriverService.Builder()
.usingDriverExecutable(
new File(System.getProperty("user.dir") + "/WiniumFolder/Winium.Desktop.Driver.exe"))
.usingPort(9999).withVerbose(true).buildDesktopService();
try {
service.start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
#Override
protected void createService() {
startService();
DesktopOptions options = new DesktopOptions();
options.setApplicationPath("C:\\Windows\\System32\\openfiles.exe");
deskClient = new WiniumDriver(service, options);
}
#Override
protected void stopService() {
if (null != service && service.isRunning()) {
service.stop();
}
}
}
public class TestCase1 {
WebDriver webClient;
WiniumDriver deskClient;
ClientFactory lists;
#BeforeTest
public void beforeTest() {
lists = FactoryManager.getIndividualProduct(EnumProductLists.CHROME);
webClient = (WebDriver) this.lists.getClient(WebDriver.class.getTypeName());
lists = FactoryManager.getIndividualProduct(EnumProductLists.DESKTOP);
deskClient = (WiniumDriver) this.lists.getClient("");
}
#Test
public void f() {
if (null != webClient) {
try {
webClient.manage().window().maximize();
webClient.get("https://uploadfiles.io/");
webClient.findElement(By.id("upload-window")).click();
String file = System.getProperty("user.dir") + "\\files\\upload.txt";
deskClient.findElement(By.name("File name:")).sendKeys(file);
deskClient.findElement(By.xpath("//*[#Name='Cancel']//preceding-sibling::*[#Name='Open']")).click();
} catch (Exception e) {
e.printStackTrace();
}
} else {
System.out.println("Client Instance is Null!");
}
}
#AfterTest
public void afterTest() {
}
}

Selenium Webdriver pdf file signature location

I find it more difficult to get solution for my issue.
Actually i am trying to upload a pdf into a website and i need to open the uploaded file and i need to place a x mark in the document, where another person needs to sign.
I have done with the file upload and now i need to open the uploaded pdf and mark the x mark for signature. The x mark will be placed once you click inside the opened document with your mouse cursor.
I have listed my code below,
Please let me know how to clear this issue.
package com.example.tests;
import java.util.regex.Pattern;
import java.util.concurrent.TimeUnit;
import org.junit.*;
import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.*;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.support.ui.WebDriverWait;
public class Dasenddoc {
private WebDriver driver;
private String baseUrl;
private boolean acceptNextAlert = true;
private StringBuffer verificationErrors = new StringBuffer();
#Before
public void setUp() throws Exception {
driver = new FirefoxDriver();
baseUrl = "https://pp.govreports.com.au/";
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
#Test
public void testDasenddoc() throws Exception {
driver.get("https://ppaccounts.govreports.com.au/");
driver.findElement(By.id("UserName")).clear();
driver.findElement(By.id("UserName")).sendKeys("vignesh#eimpact.com.au");
driver.findElement(By.id("Password")).clear();
driver.findElement(By.id("Password")).sendKeys("Viki2607");
driver.findElement(By.id("UserName")).clear();
driver.findElement(By.id("UserName")).sendKeys("vignesh2016#eimpact.com.au");
driver.findElement(By.id("btnLogin")).click();
driver.get("https://ppda.govreports.com.au/");
//Thread.sleep(5000);
//WebDriverWait wait = new WebDriverWait(driver, 15);
//wait.until(ExpectedConditions.titleContains("My Documents - Digital Authenticatiion"));
Thread.sleep(5000);
driver.findElement(By.id("newdoc")).click();
driver.findElement(By.linkText("Send a Document")).click();
driver.findElement(By.name("files")).clear();
driver.findElement(By.name("files")).sendKeys("E:\\Vignesh\\Manual\\Documents\\ITR sample files\\Individual_Tax_Return__03072013022155765.pdf");
driver.findElement(By.xpath("/html/body/div[6]/div/div[2]/div[2]/div[3]/div/form/div[1]/div/div[2]/div/table/tbody/tr/td[4]")).click();
driver.findElement(By.id("Name")).clear();
driver.findElement(By.id("Name")).sendKeys("Vignesh K S");
driver.findElement(By.xpath("/html/body/div[6]/div/div[2]/div[2]/div[3]/div/form/div[1]/div/div[2]/div/table/tbody/tr/td[5]")).click();
driver.findElement(By.id("Email")).clear();
driver.findElement(By.id("Email")).sendKeys("vignesh#eimpact.com.au");
driver.findElement(By.id("Message")).clear();
driver.findElement(By.id("Message")).sendKeys("Hi Clients");
driver.findElement(By.xpath("/html/body/div[6]/div/div[2]/div[2]/div[3]/div/form/div[1]/div/div[2]/div/table/tbody/tr/td[8]/div")).click();
driver.findElement(By.id("PvtMessage")).clear();
driver.findElement(By.id("PvtMessage")).sendKeys("Hi Viki");
driver.findElement(By.id("saveprivatemsg")).click();
driver.findElement(By.id("Continue")).click();
Thread.sleep(10000);
}
#After
public void tearDown() throws Exception {
driver.quit();
String verificationErrorString = verificationErrors.toString();
if (!"".equals(verificationErrorString)) {
fail(verificationErrorString);
}
}
private boolean isElementPresent(By by) {
try {
driver.findElement(by);
return true;
} catch (NoSuchElementException e) {
return false;
}
}
private boolean isAlertPresent() {
try {
driver.switchTo().alert();
return true;
} catch (NoAlertPresentException e) {
return false;
}
}
private String closeAlertAndGetItsText() {
try {
Alert alert = driver.switchTo().alert();
String alertText = alert.getText();
if (acceptNextAlert) {
alert.accept();
} else {
alert.dismiss();
}
return alertText;
} finally {
acceptNextAlert = true;
}
}
}

Categories