Not able to close instances of different browser using driver.quit - java

I have opened different browser instances and at the end i would like to close all the instances but when i use driver.close() or driver.quit() it is only closing the last instance of the browser. Please help.
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
public class showClose {
static WebDriver driver;
public showClose(WebDriver driver){
this.driver=driver;
}
public static void main(String[] args) {
showClose sc = new showClose(driver);
sc.IE("http://www.msn.com");
sc.Firefox("http://seleniumhq.org");
sc.Chrome("http://google.com");
driver.quit();
}
//Internet Explorer driver
public void IE(String URL){
//Set the driver property for IE
System.setProperty("webdriver.ie.driver", System.getProperty("user.dir")+"\\IEDriverServer.exe");
DesiredCapabilities ieCapabilities = DesiredCapabilities.internetExplorer();
ieCapabilities.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS, true);
//Create object of Internet explorer driver
driver = new InternetExplorerDriver(ieCapabilities);
driver.get(URL);
}
//Firefox driver
public void Firefox(String URL){
driver = new FirefoxDriver();
driver.get(URL);
}
//Chrome driver
public void Chrome(String URL){
System.setProperty("webdriver.chrome.driver", System.getProperty("user.dir")+"\\chromedriver.exe");
driver = new ChromeDriver();
driver.get(URL);
}
}

In every call of „sc.IE“, „sc.Firefox“ or „sc.Chrome“ you are overwriting the instance variable “driver”.
So the only driver that is closed by your call “driver.quit” is the last one.
If you want to close the browser after visiting the URL you would either have to do a “driver.quit” in before each call to „sc.IE“, „sc.Firefox“ or „sc.Chrome“ or manage a list of WebDrivers and close all of them.
For example you could do something like this:
import java.util.ArrayList;
import java.util.List;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
public class ShowClose {
private List<WebDriver> drivers;
public ShowClose(){
this.drivers = new ArrayList<WebDriver>();
}
public static void main(String[] args) {
ShowClose sc = new ShowClose();
sc.IE("http://www.msn.com");
sc.Firefox("http://seleniumhq.org");
sc.Chrome("http://google.com");
sc.CloseAll();
}
public void CloseAll() {
for(WebDriver d : drivers) {
d.quit();
}
}
//Internet Explorer driver
public void IE(String URL){
//Set the driver property for IE
System.setProperty("webdriver.ie.driver", System.getProperty("user.dir")+"\\IEDriverServer.exe");
DesiredCapabilities ieCapabilities = DesiredCapabilities.internetExplorer();
ieCapabilities.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS, true);
//Create object of Internet explorer driver
WebDriver driver = new InternetExplorerDriver(ieCapabilities);
driver.get(URL);
this.drivers.add(driver);
}
//Firefox driver
public void Firefox(String URL){
WebDriver driver = new FirefoxDriver();
driver.get(URL);
this.drivers.add(driver);
}
//Chrome driver
public void Chrome(String URL){
System.setProperty("webdriver.chrome.driver", System.getProperty("user.dir")+"\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get(URL);
this.drivers.add(driver);
}
}

Step1:
In Main Class declare 'List list' Interface and declare it as 'Static'
public static List<WebDriver> drivers;
Reason for Using List: It represents an ordered list of objects, meaning you can access the elements of a List in a specific order, and by an index too. You can also add the same element more than once to a List.
Step2:
Now Create a Constructor in which we will point to out current driver from the Stored List of Drivers. (I assume my class name as Test)
public Test()
{
this.drivers = new ArrayList<WebDriver>();
}
Step3:
Add a WebDriver Instance to out ArrayList for drivers in all methods of IE, Firefox and Chrome.
this.drivers.add(driver);
Step4: In main class copy all the instances of stored drivers to an object and use that object to close all opened instances.
for(WebDriver d : drivers)
{
d.quit();
}

For one thing: driver.quit() should be used if you want to close all windows. driver.close() is for a single window.
Perhaps it has something to do with the browser windows throwing an alert when they attempt to close?
See this other topic on StackOverflow for a solution to that problem

Related

Problem in doing action on new window using Selenium Webdriver with java

I am working on Selenium with java, I open a driver change its proxy and do some actions, when I tried to switch to another window and change its proxy the actions don't happened, it showed this error
java.lang.NullPointerException: Cannot invoke "org.openqa.selenium.SearchContext.findElement(org.openqa.selenium.By)" because "this.searchContext" is null
if their is someone who has already worked with switching to windows and change proxy please help
I tried to use the method swith().to but I couldn't change the proxy so I tried to use another driver.
The code, First driver:
Proxy proxy = new Proxy();
proxy.setHttpProxy("http://" + proxyy);
proxy.setSslProxy("http://" + proxyy);
ChromeOptions options = new ChromeOptions();
options.addArguments("start-maximized");
options.setCapability("proxy", proxy);
driver = new ChromeDriver(options);
randomSleep();
driver.get(JDD.url);
driver.manage().window().maximize();
Second driver:
Proxy proxy = new Proxy();
proxy.setHttpProxy("http://" + "104.227.100.66:8147");
proxy.setSslProxy("http://" + "104.227.100.66:8147");
ChromeOptions options = new ChromeOptions();
options.addArguments("start-maximized");
options.setCapability("proxy", proxy);
driver2 = new ChromeDriver(options);
randomSleep();
driver2.get(JDD.url);
driver2.manage().window().maximize();
profil("djfbadhz", "s9djq1ri28fz");
driver2.getWindowHandle();
Since you haven't provided reproducible code, I am just going to provide a simple example on how to switch tabs using Selenium 4 (and JUnit 5). If you are using Selenium 3, the way to do it is almost the same. I can provide an appropriate example if you require it.
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import java.time.Duration;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WindowType;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class ChromeTest {
#Test
void helloWorldTest () {
System.setProperty("webdriver.chrome.driver",
"F:/drivers/chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://www.google.com");
driver.manage().window().maximize();
String firstTabHandle = driver.getWindowHandle(); // save the first tab handle
// Open a new tab in the same browser session
WebDriver newTab = driver.switchTo().newWindow(WindowType.TAB);
newTab.get("https://www.msn.com/");
String secondTabHandle = driver.getWindowHandle(); // save the new tab handle
assertNotEquals(firstTabHandle, secondTabHandle); // not needed.. test the handles are different if you would like
sleep(driver);
driver.switchTo().window(firstTabHandle); // switch back to first tab
sleep(driver);
driver.switchTo().window(secondTabHandle); // switch back to new tab
sleep(driver);
driver.quit(); // end your browser session
}
private void sleep (WebDriver driver) {
new WebDriverWait(driver, Duration.ofSeconds(3))
.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//body")));
}
}
Can a web driver gain access to a window controlled by another web driver?
To my knowledge, the only way to do this is by using a driver created from the same session. You cannot start two independent sessions and hand off control to the other driver (to the best of my knowledge).
When invoking driver.switchTo().window(String windowHandle), a web driver is returned that has focus on the newly created window. HOWEVER, this is the same instance as the "driver" used to call switchTo().window(). Therefore, whether you used the returned driver or the original driver is immaterial, since they the same. Honestly, I don't know why this method returns an object at all. That said, when I ran this test using the returned driver, the test was more stable. When I used the same original instance, it tended to fail more for NoSuchElement during the second iteration. I know this could be fixed with the appropriate WebDriverWait, but I found this interesting.
To simulate the fact that this driver can interact with either window, I created the test below. The test passes three inputs to iterate over, and uses these strings to search on both Yahoo (original window) and Google (new window); all of which is done with the second (new) driver. This course of action is not necessary. Of course, each driver can interact with whichever window they created. However, in order to interact with a page, it needs to contain focus.
What does this mean related to using proxies? I do not know. All I know is that
A browser session can be interacted with by one and only one driver
Proxies (along with other options) are set before the session starts and cannot be changed after the session has begun.
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.fail;
import java.time.Duration;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.Proxy;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.WindowType;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class ChromeTest {
private static WebDriver driver;
#BeforeAll
static void setup () {
System.setProperty("webdriver.chrome.driver",
"F:/drivers/chromedriver.exe");
driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(5));
}
#AfterAll
static void teardown () {
if (driver != null) {
driver.quit();
}
}
#ParameterizedTest
#ValueSource(strings = {"dog", "cat", "birds"})
void simulateCodeTest (String input) {
driver.get("https://www.yahoo.com");
driver.manage().window().maximize();
String originalWindow = driver.getWindowHandle();
WebDriver newWindowDriver = driver.switchTo().newWindow(WindowType.WINDOW);
newWindowDriver.get("https://www.google.com");
String newWindowHandle = newWindowDriver.getWindowHandle();
newWindowDriver.switchTo().window(originalWindow);
assertTrue(originalWindow.equals(newWindowDriver.getWindowHandle()));
newWindowDriver.switchTo().window(newWindowHandle);
WebElement searchField = new WebDriverWait(newWindowDriver,
Duration.ofSeconds(5), Duration.ofMillis(10))
.until(ExpectedConditions
.elementToBeClickable(By.xpath("//input[#title='Search']")));
new Actions(newWindowDriver).sendKeys(searchField, input)
.sendKeys(Keys.ENTER).perform();
newWindowDriver.switchTo().window(originalWindow);
searchField = new WebDriverWait(newWindowDriver, Duration.ofSeconds(5),
Duration.ofMillis(10))
.until(ExpectedConditions
.elementToBeClickable(By.xpath("//input[#name='p']")));
new Actions(newWindowDriver).sendKeys(searchField, input)
.sendKeys(Keys.ENTER).perform();
WebElement searchButton =
newWindowDriver.findElement(By.xpath("//button[#type='submit']"));
searchButton.click();
}
}

Error passing WebDriver instance to another method

everyone, I'm struggling with the following situation.
Returned driver is not recognized.
I want to make a method to used it for rest of the methods for a test suite but
package acceptanceTesting
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.annotations.BeforeSuite;
public class LoginTestingStep {
#BeforeSuite
public static WebDriver driver() {
System.setProperty(WebDriverPage.webDriverAdress, WebDriverPage.webDriverPath);
WebDriver driver = new ChromeDriver();
driver.get("https://evernote.com/");
return driver;
}
public static void WaitForElementVisible(String option) {
WebDriverWait wait = new WebDriverWait(driver(), 5);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector(option)));
}
#Test
public static void UnauthotisedLogin() {
driver.manage().window().maximize();
driver.findElement(By.cssSelector(LoginTestingPage.loginButton)).click();
driver.findElement(By.cssSelector(LoginTestingPage.emailAdreesField)).sendKeys("spacesiatat#yahoo.com");
WaitForElementVisible(LoginTestingPage.continueButton);
driver.findElement(By.cssSelector(LoginTestingPage.continueButton)).click();
// TimeUnit.SECONDS.sleep(5);
// driver.close();
}
public static void AuthotisedLogin() {
}
}
Simple advice first: Do not make return anything when using TestNG annotations (like #BeforeSuite and etc.) Because everytime you want to call this method as parameter it will open new Chrome Browser.
Since you are creating driver in the inside of driver() method
No any other methods can see that there is driver already defined. Insted use it like global variable, not inside method.
public class LoginTestingStep {
WebDriver driver; //declare as global
#BeforeSuite
public static void driver() {
System.setProperty(WebDriverPage.webDriverAdress,
WebDriverPage.webDriverPath);
driver = new ChromeDriver(); //then create instance
wait = new WebDriverWait(driver, Duration.ofSeconds(5));
driver.get("https://evernote.com/");
}
public static void WaitForElementVisible(String option) {
wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector(option)));
}
#Test
public static void UnauthotisedLogin() {
driver.manage().window().maximize();
driver.findElement(By.cssSelector(LoginTestingPage.loginButton)).click();
driver.findElement(By.cssSelector(LoginTestingPage.emailAdreesField)).sendKeys("spacesiatat#yahoo.com");
WaitForElementVisible(LoginTestingPage.continueButton);
driver.findElement(By.cssSelector(LoginTestingPage.continueButton)).click();
}
}
**What I changed in your code? **
Made driver() method to be return type void instead of WebDriver return type
Deleted line that include: return driver;
Made WebDriverWait global to enable using it in other methods as well and avoiding repeating creating instance of it every time
Added 'DurationOfSeconds' to 'WebDriverWait' constructor parameter since raw usage of second is deprecated

Java selenium how to open a link from google search results?

I am new to automation testing in Selenium and i am doing some basic automation testing such as searching for something in Google and then clicking on a link which is required from the search results.
The code below, which i have produced works up until i get to the testing method. I am unable to select a link from the Google search page but i am not being shown any errors on my console. So i setup a thread on this particular line and it mentioned it could find the link name however the link name is used in the html code as i have checked on Google inspect.
Am i missing something obvious? I am relatively new to Selenium so any help is appreciated. Also i have tried mirroring some code from this users response "How to click a link by text in Selenium web driver java" but no luck!
Thanks
package com.demo.testcases;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class MyFirstTestScript {
private static WebDriver driver;
public static void main (String[] args) {
SetUp();
testing();
}
// TODO Auto-generated method stub
#setup
public static void SetUp () {
driver = new FirefoxDriver();
driver.get("http://www.google.co.uk");
System.setProperty("webdriver.gecko.driver", "usr/local/bin/geckodriver");
driver.findElement(By.name("q")).sendKeys("BBC" + Keys.ENTER);
}
#Test
public static void testing() {
driver.findElement(By.partialLinkText("BBC - Home")).click();
}
}
Once you obtain the search results for the text BBC on Google Home Page next to click() on the link containing the text BBC - Home you can use the following code block :
List <WebElement> my_list = driver.findElements(By.xpath("//div[#id='rso']//div[#class='rc']/h3[#class='r']/a"));
for (WebElement item:my_list)
{
if(item.getAttribute("innerHTML").contains("BBC - Home"))
item.click();
}
You can use this code:
public class MyFirstTestScript {
private static WebDriver driver;
private static WebDriverWait wait;
public static void main (String[] args) {
SetUp();
testing();
}
#setup
public static void SetUp () {
System.setProperty("webdriver.gecko.driver", "usr/local/bin/geckodriver");
driver = new FirefoxDriver();
wait = new WebDriverWait(driver,50);
driver.manage().window().maximize();
driver.get("http://www.google.co.uk");
wait.until(ExpectedConditions.elementToBeClickable(By.name("q")));
driver.findElement(By.name("q")).sendKeys("BBC" + Keys.ENTER);
}
#Test
public static void testing(){
wait.until(ExpectedConditions.visibilityOf(driver.findElement(By.linkText("BBC - Homepage"))));
driver.findElement(By.linkText("BBC - Homepage")).click();
}

Issue encountered executing Selenium Java code

To get started, you need to import following two packages:
org.openqa.selenium.*- contains the WebDriver class needed to instantiate a new browser loaded with a specific driver
org.openqa.selenium.firefox.FirefoxDriver - contains the FirefoxDriver class needed to instantiate a Firefox-specific driver onto the browser instantiated by the WebDriver class
If your test needs more complicated actions such as accessing another class, taking browser screenshots, or manipulating external files, definitely you will need to import more packages.
Not able to understand the code?
package newproject;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
//comment the above line and uncomment below line to use Chrome
//import org.openqa.selenium.chrome.ChromeDriver;
public class PG1 {
public static void main(String[] args) {
// declaration and instantiation of objects/variables
System.setProperty("webdriver.firefox.marionette","C:\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
//comment the above 2 lines and uncomment below 2 lines to use Chrome
//System.setProperty("webdriver.chrome.driver","G:\\chromedriver.exe");
//WebDriver driver = new ChromeDriver();
String baseUrl = "http://demo.guru99.com/selenium/newtours/";
String expectedTitle = "Welcome: Mercury Tours";
String actualTitle = "";
// launch Fire fox and direct it to the Base URL
driver.get(baseUrl);
// get the actual value of the title
actualTitle = driver.getTitle();
/*
* compare the actual title of the page with the expected one and print
* the result as "Passed" or "Failed"
*/
if (actualTitle.contentEquals(expectedTitle)){
System.out.println("Test Passed!");
} else {
System.out.println("Test Failed");
}
//close Fire fox
driver.close();
}
}
Your code looks fine. You only need to change:
This line of your code:
System.setProperty("webdriver.firefox.marionette","C:\\geckodriver.exe");
To this line:
System.setProperty("webdriver.gecko.driver","C:\\geckodriver.exe");

java selenium null pointer

I am not sure how to solve this null pointer exception. My thought was the page properties are not found as the page gets loaded which is causing this. If some one could kindly point out that would be helpful. Thanks in advance.
Code:
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class Flight {
public static WebDriver driver;
//This following section is for browser and getting the url
public static WebDriver browser(){
System.setProperty("webdriver.chrome.driver", "C:\\Users\\chq-sheikhr\\Downloads\\eclipse\\chromedriver.exe");
WebDriver driver= new ChromeDriver();
driver.get("https://www.orbitz.com/Flights");
return driver;
}
//this following section is getting the properties of the page
public static void getPageProperties(String ff,String ft, String fd, String rd){
//Flight f= new Flight(); -- I thought I was getting null pointer because properties were not found
//f.browser(); -- putting them here is how these webelements would be found and null pointer issue will be solved but NO
WebElement flyFrom= driver.findElement(By.id("flight-origin"));
WebElement flyTo= driver.findElement(By.id("flight-destination"));
WebElement flyDate= driver.findElement(By.id("flight-departing"));
WebElement returnDate= driver.findElement(By.id("flight-returnin"));
WebElement flight_search_btn= driver.findElement(By.id("search-button"));
flyFrom.sendKeys(ff);
flyTo.sendKeys(ft);
flyDate.sendKeys(fd);
returnDate.sendKeys(rd);
flight_search_btn.click();
}
// this following section will have the arguments that we will provide for flight search
public static void main (String [] args){
Flight f= new Flight();
f.browser();
f.getPageProperties("MSP", "SEA", "05/01/2017", "05/05/2017");
}
}
Error:
Only local connections are allowed.
Exception in thread "main" java.lang.NullPointerException
at Flight.getPageProperties(Flight.java:27)
at Flight.main(Flight.java:47)
You have to change
WebDriver driver= new ChromeDriver();
to
driver= new ChromeDriver();

Categories