Close all windows selenium

Selenium WebDriver: quit или close?

В этой статье речь пойдет о том как правильно останавливать работу драйвера или, другими словами, как закрыть браузер.
Запускается Selenium driver автоматически во время инициализации, для запуска у него нет отдельного метода.

Если по какой-либо причине запуск браузера не произойдет, то возникнет исключение и вебдрайвер не создастся.

А вот остановка его работы в определенное время ложится на разработчика тестов. WebDriver содержит два метода – quit() и close() , которые можно использовать для остановки работы браузера.

  • void close() — закрывает только одно текущее окно, и в случае, если это было последнее открытое окно — закрывает браузер.
  • void quit() — закрывает все открытые окна, завершает работу браузера и сервисов, и освобождает все ресурсы.

Поэтому для корректного завершения работы драйвера после выполнения теста используйте метод quit() .

Если же вам нужно закрыть отдельное открытое окно, используйте метод close(). Обратите внимание, что метод close() после закрытия одного из окон не передает управление в предыдущее открытое окно, Вы должны сделать это самостоятельно:

Если вы хотите просто уйти с текущей страницы, но не закрывать ее или браузер, можете просто использовать:

3 комментариев

Еще маленький нюанс с close() и quit() при работе с IE (с другими не проверял)
При выполнении close():
— НЕ стопается IEDriverServer.exe
— НЕ возвращаются прежние настройки прокси (если WebDriver стартовал с кастомными настройками)

К сожалению, выполнить сначала close(), потом quit() (если было открыто одно окно браузера) не удается. WebDriver на попытку quite() вываливает «session XXX does not exist». Как это красиво обойти — пока не известно

С другими браузерами тоже самое. Эти 2 метода принципиально разные, метод close() не завершает работу сервисов, он просто закрывает одну страницу (браузер уже закрывается сам собой, если страница последняя), поэтому так и происходит. Для корректного завершения работы всегда используйте quit(), он закроет все открытые окна сам. Если же необходимо использовать close() для закрытия одного окна, но оно может быть и единственным, то сделайте обвертку и проверяйте количество открытых окон:

How to close the whole browser window by keeping the webDriver active?

In my batch execution, multiple browsers with multiple tabs are getting opened for first scenario. I wanted to close all these browsers before starting second scenario.

Driver.close() is just closing one tab of the browser. Driver.quit() is closing all the browsers and also ending the WebDriver session. So , am unable to run the batch execution. Please provide a solution for this.

Читайте также:  Возникла проблема при установке драйвера windows 10

3 Answers 3

The below explanation should explain the difference between driver.close and driver.quit methods in WebDriver. I hope you find it useful.

driver.close and driver.quit are two different methods for closing the browser session in Selenium WebDriver.

Understanding both of them and knowing when to use each method is important in your test execution. Therefore, I have tried to shed some light on both of these methods.

driver.close — This method closes the browser window on which the focus is set. driver.quit close the session of webdriver while driver.close only close the current window on which selenium control is present but webdriver session not close yet, if no other window open and you call driver.close then it also close the session of webdriver.

driver.quit – This method basically calls driver.dispose a now internal method which in turn closes all of the browser windows and ends the WebDriver session gracefully.

driver.dispose — As mentioned previously, is an internal method of WebDriver which has been silently dropped according to another answer — Verification needed. This method really doesn’t have a use-case in a normal test workflow as either of the previous methods should work for most use cases.

Explanation use case: You should use driver.quit whenever you want to end the program. It will close all opened browser windows and terminates the WebDriver session. If you do not use driver.quit at the end of the program, the WebDriver session will not close properly and files would not be cleared from memory. This may result in memory leak errors.

Now In that case you need to specific browser. Below is code which will close all the child windows except the Main window.

Now here you need to modify or add the condition according to your need

Currently it is checking only if home window is equal to childwindow or not. Here you need to specify the condition like which id’s you want to close. I never tried it so just suggested you the way to achive your requirement.

How to close all opened drivers in Selenium?

I need to close all open Chrome drivers in Selenium. All my methods are closing only one of them. The reason why I need to close all drivers at the same time — in the start of my program I don’t know how many drivers I need to open, so I try to open a few drivers with same driver names in cycle.

How I opened these drivers:

How I tried to close both drivers:

First try:

Second try:

Third try:

Fourth try:

7 Answers 7

There is only a single WebDriver driver in your Code, even though you are assigning it multiple ChromeDriver() objects. So You can just close the driver once either by using driver.close() or driver.quit();

Читайте также:  Linux mint редактор изображений

and only the latest window will be closed all the previous windows will still remain (now which can’t be contacted anymore) as the only driver was closed.

driver.quit() will close all (parent+child) browser windows and end the whole session. This should work fine.

How did you initialize your driver. Did you initialize more than one driver? If so, then use quit() method for all drivers separately. Otherwise, only driver.quit() should work.

Edit:

Use driver.quit() before each new assignment.

First let’s look at your code:

Here is what is happening:

  1. You open a new Chrome instance.
  2. You then do something with that instance: navigate to a website.
  3. The next step, several things are happening: you open a new Chrome instance, and you overwrite the reference to the previous instance you opened. Essentially, at this point you lost track of the first browser you just opened!
  4. You now do something with the second opened instance: navigate to a website.

From you question it is not clear what exactly you are trying to accomplish. You have several options:

  1. Open one instance of a browser before your test. If you are using, for example JUnit, this is often done in the @Before method.
  2. Do some work in your test.
  3. Close the browser after the test. Again in JUnit, this wold be done in the @After method.

Another alternative is that you may legitimately need multiple browsers. You will need to keep track of all of them.

  1. You could create a List of drivers , and every time you open a new one, add it to that list.
  2. At the end of your tests, iterate over that list, and close all of them.

selenium: What if user close the browser or webdriver? how can I detect if the browser is closed?

Browser: Chrome webDriver

Browser Version: Chrome 63.0.3239.10(64bit)

Added below dependency :

I want check if the driver is closed by user directly, and restart the webdriver if there is no browser.

Before Driver webdriver = new ChromeDriver() codes, the webdriver is null state,

but after Driver webdriver = new ChromeDriver() code finished, even if user close the browser, webdriver is not destroyed.

so, after user close the browser, all code related to webdriver has the error:: «unreachable Exception».

I want restart the webdriver, if the browser is closed by user, but I can not detect the situation.

  1. driver!=null code is not working, because driver still exist after browser is closed by user
  2. if((driver.getWindowHandle().equals(«»)) is not working, because Chrome Unreachable Exception, because browser is closed by user

What I want to do is to check if the browser is gone, because of user?

2 Answers 2

You can perform any action on driver object, if it is throwing UnreachableBrowserException, then there is problem to communicate with the browser.

Читайте также:  What is windows event log service

The most common causes for this exception are:

  1. The provided server address to RemoteWebDriver is invalid, so the connection could not be established.
  2. The browser has died mid-test.

And you can call the following method to verify the browser is closed or not.

Let me answer your questions one by one :

What if user close the browser or webdriver : First of all Automated Test Execution shouldn’t be interuptted by Manual Intervention . It’s against all the Best Practices . If you forcefully close the Web Browser then WebDriver will throw org.openqa.selenium.WebDriverException as follows :

How can I detect if the browser is closed? : If the Automation Script handles proper initiation and closure of Web Browser you don’t need to explicitly validate if Browser is Closed or not. Cross checking dead Web Browser and Web Browser session / chores would be a pure Overhead. So a better practice would be to write Clean Code

I want restart the webdriver : Neither you can connect to the previous instance of the WebDriver nor to the previous instance of the Web Browser . You have to reinitialize again as follows :

How to close child browser window in Selenium WebDriver using Java

After I switch to a new window and complete the task, I want to close that new window and switch to the old window,

so here i written like code:

Above I written code driver.quit() or driver.close() . But I am getting error. Can anybody help me.

org.openqa.selenium.remote.SessionNotFoundException: The FirefoxDriver cannot be used after quit() was called.

7 Answers 7

To close a single browser window:

To close all (parent+child) browser windows and end the whole session:

The logic you’ve used for switching the control to popup is wrong

How the above logic will swtich the control to new window ?

Use below logic to switch the control to new window

// Perform the actions on new window

//perform remain operations in main window

Perform the click operation that opens new window

There are some instances where a window will close itself after a valid window handle has been obtained from getWindowHandle() or getWindowHandles().

There is even a possibility that a window will close itself while getWindowHandles() is running, unless you create some critical section type code (ie freeze the browser while running the test code, until all window management operations are complete)

A quicker way to check the validity of the current driver is to check the sessionId, which is made null by driver.close() or by the window closing itself.

The WebDriver needs to be cast to the remote driver interface (RemoteWebDriver) in order to obtain the sessionId, as follows:

Also note that closing the last window is equivalent to quit().

Оцените статью