How to quit ChromeDriver after Invalid Argument Exception - java

Here is my current code:
options.addArguments("--user-data-dir=Profile");
try {
driver = new ChromeDriver(options);
}
catch (Exception org.openqa.selenium.InvalidArgumentException) {
driver.quit
}
InvalidArgumentException isn't throwing until the browser window has already opened, if I try quit this in the catch block it obviously prints a nullpointer exception because the driver is never fully initialised. How can I handle an InvalidArgumentException such as the user data dir being in-use whilst also closing the chromedriver window that has already opened.

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.InvalidArgumentException;
WebDriver driver;
Boolean success;
ChromeOptions options = new ChromeOptions();
try {
options.addArguments("--user-data-dir=Profile");
success = true;
}
catch (InvalidArgumentException invArgEx) {
success = false;
}
if (success) {
driver = new ChromeDriver(options);
}

Related

How do you run a pass or fail test on your loop, identify failures, and continue passed failed attempt?

I have a program that loops through a file of IP addresses which serve as the URLs. It logs in, makes changes, saves, and logs out. I need to implement a pass or fail test to see which URLs do not complete the loop. In addition, I also need the loop to continue passed the failures while writing them to a file so I can see which did not pass. Right now, program will loop until it encounters a bad URL then throw a ERR_CONNECTION_TIMED_OUT. Any help would be appreciated as I am new to programming and SO.
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class IPLog {
WebDriver driver;
private BufferedWriter bwr1;
//Sign In
public void userLogin() throws InterruptedException {
WebDriver driver;
System.setProperty("webdriver.chrome.driver","C:\\Drivers\\chromedriver.exe");
driver = new ChromeDriver();
String data = "";
try {
BufferedReader reader = new BufferedReader(new FileReader("path"));
String line;
while((line = reader.readLine()) != null) {
data ="http://"+line;
System.out.println(data);
//open browser
driver.get(data);
driver.switchTo().frame(driver.findElement(By.name("bodyf")));
Thread.sleep(2000);
driver.findElement(By.name("username")).sendKeys("user");
Thread.sleep(2000);
driver.findElement(By.name("password")).sendKeys("pass");
driver.findElement(By.xpath("/html/body/form/span/table/tbody/tr[3]/td/p/input")).click();
//find password
driver.switchTo().frame(driver.findElement(By.name("left")));
driver.findElement(By.xpath("//*[#id=\"4050000\"]/a")).click();
driver.findElement(By.xpath("//*[#id=\"4050000\"]/table/tbody/tr[3]/td[2]/a")).click();
//change password
driver.switchTo().parentFrame();
driver.switchTo().frame(1);
Thread.sleep(2000);
driver.findElement(By.xpath("/html/body/form/p[1]/table/tbody/tr[2]/td[2]/input")).sendKeys("newpass");
Thread.sleep(2000);
driver.findElement(By.xpath("/html/body/form/p[1]/table/tbody/tr[3]/td[2]/input")).sendKeys("newpass");
Thread.sleep(2000);
driver.findElement(By.xpath("/html/body/form/p[2]/input[2]")).click();
//save and logout
Thread.sleep(3000);
driver.switchTo().alert().accept();
driver.switchTo().parentFrame();
driver.switchTo().frame(driver.findElement(By.name("left")));
driver.findElement(By.id("sysLogout")).click();
Thread.sleep(3000);
driver.switchTo().alert().accept();
//completion test
FileWriter writer = new FileWriter("path");
BufferedWriter bwr = (new BufferedWriter(writer));
bwr.write(data + "- Test Passed\n");
bwr.write("\n");
try {
FileWriter writer1 = new FileWriter("path");
bwr1 = (new BufferedWriter(writer1));
bwr1.write(data + "- Test Failed");
bwr1.write("\n");
System.out.println("fail");
}
catch (Exception e) {
e.printStackTrace();
}
}
}
catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws InterruptedException, IOException {
IPLog obj = new IPLog();
obj.userLogin();
}
}
What you can do is add a try-catch for each line you are processing. For instance, you can rewrite your loop as follows:
FileWriter writer = new FileWriter("path");
BufferedWriter bwr = (new BufferedWriter(writer));
while((line = reader.readLine()) != null) {
data ="http://"+line;
System.out.println(data);
try {
doActionLine(data);
//add test passed
bwr.write(data + "- Test Passed\n");
bwr.write("\n");
} catch (Exception e) {
//add test failed
bwr.write(data + "- Test Failed\n");
bwr.write("\n");
}
}
As you can see, doActionLine funcion has encapsulated the checks:
private void doActionLine(String data) throws InterruptedException {
//open browser
driver.get(data);
driver.switchTo().frame(driver.findElement(By.name("bodyf")));
Thread.sleep(2000);
driver.findElement(By.name("username")).sendKeys("user");
Thread.sleep(2000);
driver.findElement(By.name("password")).sendKeys("pass");
driver.findElement(By.xpath("/html/body/form/span/table/tbody/tr[3]/td/p/input")).click();
//find password
driver.switchTo().frame(driver.findElement(By.name("left")));
driver.findElement(By.xpath("//*[#id=\"4050000\"]/a")).click();
driver.findElement(By.xpath("//*[#id=\"4050000\"]/table/tbody/tr[3]/td[2]/a")).click();
//change password
driver.switchTo().parentFrame();
driver.switchTo().frame(1);
Thread.sleep(2000);
driver.findElement(By.xpath("/html/body/form/p[1]/table/tbody/tr[2]/td[2]/input")).sendKeys("newpass");
Thread.sleep(2000);
driver.findElement(By.xpath("/html/body/form/p[1]/table/tbody/tr[3]/td[2]/input")).sendKeys("newpass");
Thread.sleep(2000);
driver.findElement(By.xpath("/html/body/form/p[2]/input[2]")).click();
//save and logout
Thread.sleep(3000);
driver.switchTo().alert().accept();
driver.switchTo().parentFrame();
driver.switchTo().frame(driver.findElement(By.name("left")));
driver.findElement(By.id("sysLogout")).click();
Thread.sleep(3000);
driver.switchTo().alert().accept();
}
I hope this help you.

Selenium program returning NoSuchElementException no matter what element query type I use?

I have a stock data site that I am trying to use Selenium to parse data from. I feel like I'm really close, but something in my code is causing the program to return a NoSuchElementException. I can do a JS query of the page (https://www.cnbc.com/quotes/?symbol=.DJI) using my desired element from the Chrome developer console as follows:
document.getElementsByClassName("last original ng-binding")
However, doing a similar query in my Java-based Selenium program to find the element by class name returns this exception. Why that be when I'm using the same class name as the JS query? I've tried doing queries by xpath and css as well with a similar error. Here's my code I have:
//Built in Java 1.7 due to Selenium compatabilities
//Import packages
import java.io.File;
import java.util.Scanner;
import org.openqa.selenium.By;
import org.openqa.selenium.By.ByClassName;
import org.openqa.selenium.InvalidArgumentException;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class Tester {
//Instantiate common variables
WebDriver driver;
String url;
Scanner input;
boolean error;
int uses = 0;
public void invokeBrowser() {
try {
//Point Selenium to Chrome Driver file
File file = new File("C:\\Users\\zrr81\\eclipse-workspace\\WebScraper\\Selenium\\chromedriver.exe");
System.setProperty("webdriver.chrome.driver", file.getAbsolutePath());
//Initialize Chrome driver and perform maintenance functions
driver = new ChromeDriver();
driver.manage().deleteAllCookies();
uses ++;
//Execute parseData code
parseData();
} catch (Exception e) {
e.printStackTrace();
}
}
//Try to connect, include catch for typos/errors
public void parseData() {
try {
input = new Scanner(System.in);
System.out.println("Enter the url you would like to connect to: ");
String url = input.nextLine();
driver.get(url);
elementLocator();
}
//Specific catch for an invalid site (e.g. a dead link)
catch(InvalidArgumentException e) {
System.out.println("He's dead Jim! :/");
}
//Catch for all other exceptions
catch(Exception ex) {
System.out.println("Check your syntax partner!");
}
}
public void elementLocator() {
try {
//driver.findElement(By.linkText("DJIA</a>")).click();
String stock = driver.findElement(By.className("last original ng-binding")).toString();
System.out.println(stock);
//Catch specific exception for html element not found
} catch (NoSuchElementException e) {
System.out.println("Selected element not found");
error = true;
//General exception catch
} catch (Exception ex) {
ex.printStackTrace();
}
finally {
if (error==true) {
closeBrowser();
}
}
}
public void closeBrowser() {
//If only 1 window is open, close the window
if(uses == 1) {
driver.close();
}
//Otherwise, close the whole browser
else {
driver.quit();
}
}
//Invoke methods
public static void main(String[] args) {
Tester myObj = new Tester();
myObj.invokeBrowser();
}
}
NoSuchElement exception occurs when element is not present on the web page for procession during Runtime. Also , your findElement is wrong in your code. Please refer below code to print 23,433.57 from your webpage.
WebElement TxtBoxContent = driver.findElement(By.cssSelector("td > .last:nth-child(1)"));
System.out.println("Text " +TxtBoxContent.getText());

First test case is not getting complete and it proceed for the next one.How can i resolve this?

I have one test case, in which i have to click on a button to complete my test case but it's response is little slow and my code proceed to the next case prior to the completion of this test case.So My question is how can mark my first test case completed so that next test case run easily.
Can anyone please help and thanks in advance.My code is:
package com.dristhi.automate.testing;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.Select;
public class CreateInteraction {
WebDriver driver;
public CreateInteraction(WebDriver driver) {
// TODO Auto-generated constructor stub
this.driver = driver;
}
public void testCreateInteraction() {
if (driver != null) {
try {
Thread.sleep(5000);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// Open create interaction
driver.findElement(By.id("automationTestingIdCreateTicketLink")).click();
List<WebElement> collapsabletab = driver.findElements(By.className("collapsible-header"));
for (WebElement webElement : collapsabletab) {
System.out.println(webElement.getText());
if (webElement.getText().equals("Create Ticket")) {
webElement.click();
break;
}
}
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// select Email from media drop down
WebElement media = driver.findElement(By.id("automationTestingIdMediaSelection"));
WebElement mediaDropdown = media.findElement(By.cssSelector(".gwt-ListBox.browser-default"));
mediaDropdown.click();
Select mediaSelect = new Select(mediaDropdown);
mediaSelect.selectByValue("email");
// Select queue to create the ticket
WebElement queue = driver.findElement(By.id("automationTestinfIdQueueSelectionForTicket"));
WebElement queuedropdown = queue.findElement(By.cssSelector(".gwt-ListBox.browser-default"));
queuedropdown.click();
Select queueSelect = new Select(queuedropdown);
queueSelect.selectByVisibleText("support");
// Enter To ID value
WebElement enterToId = driver.findElement(By.id("automationTestingIdForToEmailInCreateTicket"));
WebElement enterToIdValue = enterToId.findElement(By.tagName("div"));
enterToIdValue.click();
WebElement emailToIDInput = enterToIdValue.findElement(By.tagName("input"));
emailToIDInput.sendKeys("ashwanirao#ameyo.com");
emailToIDInput.sendKeys(Keys.ENTER);
// Enter subject for the test Email
WebElement entersubject = driver.findElement(By.id("automationTestingIdForSubjectInCreateTicket"));
WebElement enterSubjectValue = entersubject.findElement(By.className("gwt-TextBox"));
enterSubjectValue.sendKeys("First time in the history of drishti to Automate the Manual testing");
// Click on save button to create the ticket
driver.findElement(By.id("automationTestingIdSaveTopTicketButton")).click();
}
}
}

Exception on running IE web Driver

I'm new in java, using it for automatic tests. Please help me what I'm doing wrong with this code?
public static WebDriver driver = null;
public static WebDriver getDriver() {
if (driver == null) {
File fileIE = new File("src//test/java/iedriver.exe");
System.setProperty("webdriver.ie.driver", fileIE.getAbsolutePath());
}
try {
driver = new InternetExplorerDriver();
}
catch (Exception e)
e.printStackTrace();
}
Try to add DesiredCapabilities to your code.
if (driver == null) {
File fileIE = new File("src//test/java/iedriver.exe");
System.setProperty("webdriver.ie.driver", fileIE.getAbsolutePath());
DesiredCapabilities ieCapabilities = DesiredCapabilities.internetExplorer();
try {
driver = new InternetExplorerDriver(ieCapabilities);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
the DesiredCapabilities help to set properties for the WebDriver. A typical usecase would be to set the path for any type of the WebDriver if your local installation doesn't correspond to the default settings.
You can read about class DesiredCapabilities and about its' using here: DesiredCapabilities

Exception Selenium Webdriver TestNg [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
Tried to create properties file and retrieving information from it , but am getting an java.lang.NullPointerException ,also tried try and catch , as am very new to coding, can anyone please let me know why am getting null pointer Exception.
package ObjectRepository;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Properties;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.Test;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.AfterTest;
public class PropertiesGuru99Bank {
WebDriver driver;
#Test
public void f() {
File file=new File("E:\\selenium\\Rahul\\Project\\src\\ObjectRepository\\object.properties");
FileInputStream f=null;
try {
f=new FileInputStream(file);
} catch (Exception e) {
// TODO: handle exception
System.out.println(e.getStackTrace());
}
Properties prop=new Properties();
try {
prop.load(f);
} catch (Exception e) {
// TODO: handle exception
System.out.println(e.getStackTrace());
}
driver.get(prop.getProperty("url"));
driver.findElement(By.id(prop.getProperty("id"))).sendKeys("rahul");
}
#BeforeTest
public void beforeTest() {
System.setProperty("webdriver.chrome.driver", "E:\\selenium\\lib\\chromedriver_win32\\chromedriver.exe");
new ChromeDriver();
}
#AfterTest
public void afterTest() {
}
}
Small typo probably. You are not instantiating the driver. new ChromeDriver(); does not instantite the driver. do driver = new ChromeDriver(); or shown below after setting the driver exe to system property.
import org.testng.annotations.Test;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.AfterTest;
public class PropertiesGuru99Bank {
WebDriver driver;
#Test
public void f() {
File file=new File("E:\\selenium\\Rahul\\Project\\src\\ObjectRepository\\object.properties");
FileInputStream f=null;
try {
f=new FileInputStream(file);
} catch (Exception e) {
// TODO: handle exception
System.out.println(e.getStackTrace());
}
Properties prop=new Properties();
try {
prop.load(f);
} catch (Exception e) {
// TODO: handle exception
System.out.println(e.getStackTrace());
}
driver.get(prop.getProperty("url"));
driver.findElement(By.id(prop.getProperty("id"))).sendKeys("rahul");
}
#BeforeTest
public void beforeTest() {
System.setProperty("webdriver.chrome.driver", "E:\\selenium\\lib\\chromedriver_win32\\chromedriver.exe");
//this is what you are missing
driver = new ChromeDriver();
}
#AfterTest
public void afterTest() {
}
}

Categories

Resources