「close」を実行することでウィンドウを閉じることが出来ます。
閉じることが出来るのはあくまでnewで作成したインスタンスウインドウのみで、インスタンスウインドウのタブで追加したウインドウは閉じることが出来ません。また、newで複数のウインドウを作成した場合、それぞれウインドウにcloseを実行して閉じる必要があります。
説明
◆メソッド ・void close() ◆使用形態 ・driver.close() ◆備考 ・newで作成したインスタンスウインドウのみを閉じる ◆関連項目 ・ウインドウを閉じる(全てのウインドウ) ・ブラウザを履歴中で一段階戻す
サンプル
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){
}
//newで作成したwindowのみを閉じる
driver.close();
}
}※selenium version 4.1.4で動作確認をしています(ブラウザのUIや属性値などが変更された場合、実行結果が異なる可能性があります)
実行結果

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


