「quit」を実行することで全てのウィンドウを閉じることが出来ます。
newで作成したウインドウだけでなく、ウインドウからタブで追加したウインドウに関しても同時に閉じることが出来ます。しかし、newで複数のウインドウを作成した場合は、それぞれのウインドウに対して「quit」を実行して閉じる必要があります。
説明
◆メソッド ・void quit() ◆使用形態 ・driver.quit() ◆備考 ・ウインドウを全て閉じる ◆関連項目 ・ブラウザを履歴中で一段階戻す ・ブラウザを履歴中で一段階進める
サンプル
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;
public class WebTest{
public static void main(String[] args){
//Chrome制御のためChromeDriverのパスを指定
System.setProperty("webdriver.chrome.driver",
"D:\\AutoTest\\chromedriver.exe");
//Chromeを起動する
WebDriver driver = new ChromeDriver();
//指定したURLに遷移する
driver.get("https://www.google.co.jp");
//リンクテキスト名がGmailのリンク要素を取得
WebElement element = driver.findElement(By.linkText("Gmail"));
//Controlキーを押下しながら"Gmail"のリンクをクリック
Actions action = new Actions(driver);
action.keyDown(Keys.CONTROL)
.click(element)
.perform();
//少し待機する
try{
Thread.sleep(3000);
}catch(InterruptedException e){
}
//windowを全て閉じる
driver.quit();
}
}※selenium version 4.1.4で動作確認をしています(ブラウザのUIや属性値などが変更された場合、実行結果が異なる可能性があります)
実行結果

動画デモ
※字幕をONにすると解説のテロップが表示されます※


