• Selenium Video Tutorials

Selenium WebDriver - 瀏覽器上下文



Selenium Webdriver 可用於瀏覽器上下文。有多個 API 用於瀏覽器上下文命令。可以使用瀏覽器上下文執行的一些操作包括開啟新視窗、標籤頁,利用已開啟的視窗,開啟 URL 等等。

建立瀏覽器上下文

為了建立一個瀏覽器上下文,我們將使用 ChromeOptions 類,然後將 capability webSocketUrl 設定為 true 值,並將它的引用傳遞給 Webdriver。請注意,我們還需要匯入以下語句才能使用瀏覽器上下文的方法。

import org.openqa.selenium.bidi.browsingcontext.BrowsingContext.

在使用瀏覽器上下文命令的 API 執行測試時,將開啟一個標題為 **BiDi-CDP Mapper** 的標籤頁,其中包含訊息 - **BiDi-CDP Mapper 正在控制此標籤頁以及除錯資訊**。這將證明自動化測試正在使用瀏覽器上下文。

Selenium WebDriver Browsing Context 1

下一個標籤頁將開啟自動化測試觸發的應用程式。

Selenium WebDriver Browsing Context 2

Selenium 中的瀏覽器上下文是 Selenium 4.x 版本中提供的一項功能。為了利用瀏覽器上下文命令上的所有 API,建議使用 Selenium 4.16.x 版本的 Selenium Maven 依賴項。

新增到 **pom.xml** 的瀏覽器上下文依賴項

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
   http://maven.apache.org/xsd/maven-4.0.0.xsd">
   
   <modelVersion>4.0.0</modelVersion>
   <groupId>org.example</groupId>
   <artifactId>SeleniumJava</artifactId>
   <version>1.0-SNAPSHOT</version>
   
   <properties>
      <maven.compiler.source>16</maven.compiler.source>
      <maven.compiler.target>16</maven.compiler.target>
      <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
   </properties>
   
   <!-- https://mvnrepository.com/artifact/org.seleniumhq.selenium/selenium-java -->
   <dependencies>
      <dependency>
         <groupId>org.seleniumhq.selenium</groupId>
         <artifactId>selenium-java</artifactId>
         <version>4.16.1</version>
      </dependency>
      
      <!-- https://mvnrepository.com/artifact/org.testng/testng -->
      <dependency>
         <groupId>org.testng</groupId>
         <artifactId>testng</artifactId>
         <version>7.9.0</version>
         <scope>test</scope>
      </dependency>
   </dependencies>
</project>

在新視窗中建立瀏覽器上下文並導航到 URL

讓我們來看一個例子,我們將開啟一個瀏覽器,然後開啟另一個新視窗並啟動一個具有以下 URL 的應用程式以建立瀏覽器上下文:

https://tutorialspoint.tw/selenium/.

**BrowsingContextNewWindows.java** 中的程式碼實現

package org.example;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WindowType;
import org.openqa.selenium.bidi.browsingcontext.BrowsingContext;
import org.openqa.selenium.bidi.browsingcontext.NavigationResult;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import java.util.concurrent.TimeUnit;

public class BrowsingContextNewWindows {
   public static void main(String[] args) throws InterruptedException {

      // object of ChromeOptions
      ChromeOptions opt = new ChromeOptions();
      opt.setCapability("webSocketUrl", true);

      // Initiate the Webdriver
      WebDriver driver = new ChromeDriver(opt);

      // adding implicit wait of 15 secs
      driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);

      // launching a browser and open a URL
      driver.get("https://tutorialspoint.tw/selenium/practice/check-box.php");

      // open browsing context in new window
      BrowsingContext bc = new BrowsingContext(driver, WindowType.WINDOW);

      // obtain id of browsing context in new window
      String text = bc.getId();
      System.out.println("Id of browsing context in new window: " + text);

      // navigate to new url in the new window
      NavigationResult i = bc.navigate("https://tutorialspoint.tw/selenium/practice/buttons.php");

      // get new URL opened in the new window
      System.out.println("Get URL: " + i.getUrl());

      // Quitting browser
      driver.quit();
   }
}

它將顯示以下 **輸出**:

Id of browsing context in new window:
14CC57B70B48D044482821778B560618
Get URL: 
https://tutorialspoint.tw/selenium/practice/buttons.php

Process finished with exit code 0

在上面的示例中,我們打開了一個瀏覽器,然後開啟另一個新視窗並啟動了一個具有以下 URL 的應用程式以建立瀏覽器上下文。我們在控制檯中獲得了新視窗的瀏覽器上下文 ID 和啟動的 URL,訊息為 - **新視窗中瀏覽器上下文的 ID:14CC57B70B48D044482821778B560618** 和 **獲取 URL:** https://tutorialspoint.tw/selenium/

最後,收到訊息 **程序已完成,退出程式碼為 0**,表示程式碼已成功執行。

在新標籤頁中建立瀏覽器上下文並導航到 URL

讓我們來看一個例子,我們將開啟一個瀏覽器,然後開啟另一個新標籤頁並在那裡啟動一個具有以下 URL 的應用程式以建立瀏覽器上下文:https://tutorialspoint.tw/selenium/

**BrowsingContextNewTabs.java** 中的程式碼實現

package org.example;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WindowType;
import org.openqa.selenium.bidi.browsingcontext.BrowsingContext;
import org.openqa.selenium.bidi.browsingcontext.NavigationResult;
import org.openqa.selenium.bidi.browsingcontext.ReadinessState;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import java.util.concurrent.TimeUnit;

public class BrowsingContextNewTabs {
   public static void main(String[] args) throws InterruptedException {

      // object of ChromeOptions
      ChromeOptions opt = new ChromeOptions();
      opt.setCapability("webSocketUrl", true);

      // Initiate the Webdriver
      WebDriver driver = new ChromeDriver(opt);

      // adding implicit wait of 15 secs
      driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);

      // launching a browser and open a URL
      driver.get("https://tutorialspoint.tw/selenium/practice/check-box.php");

      // open browsing context in new tab
      BrowsingContext bc = new BrowsingContext(driver, WindowType.TAB);

      // obtain id of browsing context in new tab
      String text = bc.getId();
      System.out.println("Id of browsing context in new tab: " + text);

      // navigate to new url in the new tab in readiness state
      NavigationResult i = bc.navigate("https://tutorialspoint.tw/selenium/practice/buttons.php",
      ReadinessState.COMPLETE);

      // get new URL opened in the new tab
      System.out.println("Get URL: " + i.getUrl());

      // Quitting browser
      driver.quit();
   }
}

它將顯示以下 **輸出**:

Id of browsing context in new tab:
E7D9C6C1EA830EE2E968EFFDAE800EE2
Get URL:
 https://tutorialspoint.tw/selenium/practice/buttons.php

Process finished with exit code 0

在上面的示例中,我們打開了一個瀏覽器,然後開啟另一個新標籤頁並啟動了一個具有以下 URL 的應用程式以建立瀏覽器上下文。我們在控制檯中獲得了新標籤頁的瀏覽器上下文 ID 和啟動的 URL,訊息為 - **新標籤頁中瀏覽器上下文的 ID:E7D9C6C1EA830EE2E968EFFDAE800EE2** 和 **獲取 URL:** https://tutorialspoint.tw/selenium/

最後,收到訊息 **程序已完成,退出程式碼為 0**,表示程式碼已成功執行。

使用現有視窗/標籤頁控制代碼建立瀏覽器上下文

讓我們來看一個例子,我們將使用現有視窗/標籤頁建立一個瀏覽器上下文。

**BrowsingContextNewTab.java** 中的程式碼實現

package org.example;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.bidi.browsingcontext.BrowsingContext;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import java.util.concurrent.TimeUnit;

public class BrowsingContextNewTab {
   public static void main(String[] args) throws InterruptedException {

      // object of ChromeOptions
      ChromeOptions opt = new ChromeOptions();
      opt.setCapability("webSocketUrl", true);

      // Initiate the Webdriver
      WebDriver driver = new ChromeDriver(opt);

      // adding implicit wait of 15 secs
      driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);

      // launching a browser and open a URL
      driver.get("https://tutorialspoint.tw/selenium/practice/check-box.php");

      // get window handle id
      String windowID = driver.getWindowHandle();

      // open browsing context in new tab/window
      BrowsingContext bc = new BrowsingContext(driver, windowID);

      // obtain id of browsing context in new tab/window
      String text = bc.getId();
      System.out.println("Id of browsing context in new tab/window: " + text);

      // Quitting browser
      driver.quit();
   }
}

它將顯示以下 **輸出**:

Id of browsing context in new tab/window:
E5EB8BA6EBAFBA14561CC8EB23360034

Process finished with exit code 0

在上面的示例中,我們使用現有視窗/標籤頁控制代碼建立了瀏覽器上下文。我們在控制檯中獲得了瀏覽器上下文 ID,訊息為 - **新視窗/標籤頁中的瀏覽器上下文 ID:E5EB8BA6EBAFBA14561CC8EB23360034**。

最後,收到訊息 **程序已完成,退出程式碼為 0**,表示程式碼已成功執行。

開啟具有參考瀏覽器上下文的新視窗後建立瀏覽器上下文

讓我們來看一個例子,我們將透過開啟一個具有參考瀏覽器上下文的新視窗來建立一個瀏覽器上下文。

**BrowsingContextNewWindow.java** 中的程式碼實現

package org.example;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WindowType;
import org.openqa.selenium.bidi.browsingcontext.BrowsingContext;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import java.util.concurrent.TimeUnit;

public class BrowsingContextNewWindow {
   public static void main(String[] args) throws InterruptedException {

      // object of ChromeOptions
      ChromeOptions opt = new ChromeOptions();
      opt.setCapability("webSocketUrl", true);

      // Initiate the Webdriver
      WebDriver driver = new ChromeDriver(opt);

      // adding implicit wait of 15 secs
      driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);

      // launching a browser and open a URL
      driver.get("https://tutorialspoint.tw/selenium/practice/check-box.php");

      // get window handle id
      String windowID = driver.getWindowHandle();

      // open browsing context in new window using  browsing context
      BrowsingContext bc = new BrowsingContext(driver, WindowType.WINDOW, windowID);

      // obtain id of browsing context
      String text = bc.getId();
      System.out.println("Id of browsing context in new window: " + text);

      // Quitting browser
      driver.quit();
   }
}

它將顯示以下 **輸出**:

Id of browsing context in new window: 
F82CF86144C26AEA4168F672C11B8C92

Process finished with exit code 0

在上面的示例中,我們在開啟具有參考瀏覽器上下文的新視窗後建立了瀏覽器上下文。我們在控制檯中獲得了瀏覽器上下文 ID,訊息為 - **視窗中瀏覽器上下文的 ID:F82CF86144C26AEA4168F672C11B8C92**。

最後,收到訊息 **程序已完成,退出程式碼為 0**,表示程式碼已成功執行。

開啟具有參考瀏覽器上下文的新標籤頁後建立瀏覽器上下文

讓我們來看一個例子,我們將透過開啟一個具有參考瀏覽器上下文的新標籤頁來建立一個瀏覽器上下文。

**BrowsingContextNewTab.java** 中的程式碼實現

package org.example;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WindowType;
import org.openqa.selenium.bidi.browsingcontext.BrowsingContext;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import java.util.concurrent.TimeUnit;

public class BrowsingContextNewTab {
   public static void main(String[] args) throws InterruptedException {

      // object of ChromeOptions
      ChromeOptions opt = new ChromeOptions();
      opt.setCapability("webSocketUrl", true);

      // Initiate the Webdriver
      WebDriver driver = new ChromeDriver(opt);

      // adding implicit wait of 15 secs
      driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);

      // launching a browser and open a URL
      driver.get("https://tutorialspoint.tw/selenium/practice/check-box.php");

      // get window handle id
      String windowID = driver.getWindowHandle();

      // open browsing context in new tab using browsing context
      BrowsingContext bc = new BrowsingContext(driver, WindowType.TAB, windowID);

      // obtain id of browsing context
      String text = bc.getId();
      System.out.println("Id of browsing context in new tab: " + text);

      // Quitting browser
      driver.quit();
   }
}

它將顯示以下 **輸出**:

Id of browsing context in new tab: 
C88F54A24AF3C6DE71C5B5E37913BA77

Process finished with exit code 0

在上面的示例中,我們在開啟具有參考瀏覽器上下文的新標籤頁後建立了瀏覽器上下文。我們在控制檯中獲得了瀏覽器上下文 ID,訊息為 - **標籤頁中瀏覽器上下文的 ID:C88F54A24AF3C6DE71C5B5E37913BA77**。

最後,收到訊息 **程序已完成,退出程式碼為 0**,表示程式碼已成功執行。

獲取瀏覽器上下文樹

讓我們來看一個例子,我們將從父瀏覽器上下文開始獲取每個瀏覽器上下文。

**BrowsingContextTree.java** 中的程式碼實現

package org.example;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.bidi.browsingcontext.BrowsingContext;
import org.openqa.selenium.bidi.browsingcontext.BrowsingContextInfo;
import org.openqa.selenium.bidi.browsingcontext.ReadinessState;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;

import java.util.List;
import java.util.concurrent.TimeUnit;
public class BrowsingContextTree {
   public static void main(String[] args) throws InterruptedException {

      // object of ChromeOptions
      ChromeOptions opt = new ChromeOptions();
      opt.setCapability("webSocketUrl", true);

      // Initiate the Webdriver
      WebDriver driver = new ChromeDriver(opt);

      // adding implicit wait of 15 secs
      driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);

      // launching a browser and open a URL
      driver.get("https://tutorialspoint.tw/selenium/practice/check-box.php");

      // get window handle id
      String windowID = driver.getWindowHandle();

      // open browsing context in new tab/window
      BrowsingContext bc = new BrowsingContext(driver, windowID);

      // open another URL
      bc.navigate("https://tutorialspoint.tw/selenium/practice/buttons.php", ReadinessState.COMPLETE);

      // list of browsing context tree
      List<BrowsingContextInfo> tree = bc.getTree();

      // obtain total browsing context tree
      int size = tree.size();
      System.out.println("Total browsing contexts: " + size);

      // obtain total children
      BrowsingContextInfo c = tree.get(0);
      int size1 = c.getChildren().size();
      System.out.println("Total children: " + size1);

      // Quitting browser
      driver.quit();
   }
}

它將顯示以下 **輸出**:

Total browsing contexts: 1
Total children: 0

Process finished with exit code 0

獲取具有深度值的瀏覽器上下文樹

讓我們來看一個例子,我們將從父瀏覽器上下文開始獲取每個瀏覽器上下文以及深度值。

**BrowsingContextTreeDepth.java** 中的程式碼實現

package org.example;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.bidi.browsingcontext.BrowsingContext;
import org.openqa.selenium.bidi.browsingcontext.BrowsingContextInfo;
import org.openqa.selenium.bidi.browsingcontext.ReadinessState;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;

import java.util.List;
import java.util.concurrent.TimeUnit;

public class BrowsingContextTreeDepth {
   public static void main(String[] args) throws InterruptedException {

      // object of ChromeOptions
      ChromeOptions opt = new ChromeOptions();
      opt.setCapability("webSocketUrl", true);

      // Initiate the Webdriver
      WebDriver driver = new ChromeDriver(opt);

      // adding implicit wait of 15 secs
      driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);

      // launching a browser and open a URL
      driver.get("https://tutorialspoint.tw/selenium/practice/check-box.php");

      // get window handle id
      String windowID = driver.getWindowHandle();
      System.out.println("Window Handle Id: " + windowID);

      // open browsing context in new tab/window
      BrowsingContext bc = new BrowsingContext(driver, windowID);

      // open another URL
      bc.navigate("https://tutorialspoint.tw/selenium/practice/buttons.php", ReadinessState.COMPLETE);

      // list of browsing context tree with depth value
      List<BrowsingContextInfo> tree = bc.getTree(0);

      // obtain total browsing context tree
      int size = tree.size();
      System.out.println("Total browsing contexts: " + size);

      // obtain total children
      BrowsingContextInfo c = tree.get(0);
      List children = c.getChildren();
      System.out.println("Total children: " + children);
      System.out.println("Browsing Context id: " + c.getId());

      // Quitting browser
      driver.quit();
   }
}

它將顯示以下 **輸出**:

Window Handle Id: DE5E963CFFCC9A42A5F7A4903BF0C12C
Total browsing contexts: 1
Total children: null
Browsing Context id: DE5E963CFFCC9A42A5F7A4903BF0C12C

Process finished with exit code 0

獲取所有頂級瀏覽器上下文

讓我們來看一個例子,我們將獲取所有頂級瀏覽器上下文。

**BrowsingContextTopLevel.java** 中的程式碼實現

package org.example;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WindowType;
import org.openqa.selenium.bidi.browsingcontext.BrowsingContext;
import org.openqa.selenium.bidi.browsingcontext.BrowsingContextInfo;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import java.util.List;
import java.util.concurrent.TimeUnit;

public class BrowsingContextTopLevel {
   public static void main(String[] args) throws InterruptedException {

      // object of ChromeOptions
      ChromeOptions opt = new ChromeOptions();
      opt.setCapability("webSocketUrl", true);

      // Initiate the Webdriver
      WebDriver driver = new ChromeDriver(opt);

      // adding implicit wait of 15 secs
      driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);

      // launching a browser and open a URL
      driver.get("https://tutorialspoint.tw/selenium/practice/check-box.php");

      // get window handle id
      String windowID = driver.getWindowHandle();

      // open browsing context in new tab/window
      BrowsingContext bc1 = new BrowsingContext(driver, windowID);

      // open another browsing context in new window
      BrowsingContext bc2 = new BrowsingContext(driver, WindowType.WINDOW);

      // list of every top level browsing contexts
      List<BrowsingContextInfo> tree = bc1.getTopLevelContexts();

      // obtain total browsing context tree
      int size = tree.size();
      System.out.println("Total top level browsing context: " + size);

      // Quitting browser
      driver.quit();
   }
}

它將顯示以下 **輸出**:

Total top level browsing context: 2

Process finished with exit code 0

在上面的示例中,我們在控制檯中獲得了所有頂級瀏覽器上下文,訊息為 - **頂級瀏覽器上下文總數:2**。

最後,收到訊息 **程序已完成,退出程式碼為 0**,表示程式碼已成功執行。

關閉視窗瀏覽器上下文

讓我們來看一個例子,我們將使用 close() 方法關閉視窗瀏覽器上下文。

**BrowsingContextWindowClose.java** 中的程式碼實現

package org.example;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WindowType;
import org.openqa.selenium.bidi.browsingcontext.BrowsingContext;
import org.openqa.selenium.bidi.browsingcontext.BrowsingContextInfo;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import java.util.List;
import java.util.concurrent.TimeUnit;

public class BrowsingContextWindowClose {
   public static void main(String[] args) throws InterruptedException {

      // object of ChromeOptions
      ChromeOptions opt = new ChromeOptions();
      opt.setCapability("webSocketUrl", true);

      // Initiate the Webdriver
      WebDriver driver = new ChromeDriver(opt);

      // adding implicit wait of 15 secs
      driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);

      // launching a browser and open a URL
      driver.get("https://tutorialspoint.tw/selenium/practice/check-box.php");

      // open browsing context in new window
      BrowsingContext bc1 = new BrowsingContext(driver, WindowType.WINDOW);

      // open another browsing context in new window
      BrowsingContext bc2 = new BrowsingContext(driver, WindowType.WINDOW);

      // list of every top level browsing contexts
      List<BrowsingContextInfo> tree = bc1.getTopLevelContexts();

      // obtain total browsing context tree
      int size = tree.size();
      System.out.println("Total top level browsing context before closing: " + size);

      // close one browsing context
      bc2.close();

      // obtain total browsing context tree after closing one
      List<BrowsingContextInfo> tree1 = bc1.getTopLevelContexts();
      int size1 = tree1.size();
      System.out.println("Total top level browsing context after closing: " + size1);

      // Quitting browser
      driver.quit();
   }
}

它將顯示以下 **輸出**:

Total top level browsing context before closing: 3
Total top level browsing context after closing: 2

Process finished with exit code 0

關閉標籤頁瀏覽器上下文

讓我們來看一個例子,我們將使用 close() 方法關閉標籤頁瀏覽器上下文。

**BrowsingContextTabClose.java** 中的程式碼實現

package org.example;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WindowType;
import org.openqa.selenium.bidi.browsingcontext.BrowsingContext;
import org.openqa.selenium.bidi.browsingcontext.BrowsingContextInfo;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import java.util.List;
import java.util.concurrent.TimeUnit;

public class BrowsingContextTabClose {
   public static void main(String[] args) throws InterruptedException {

      // object of ChromeOptions
      ChromeOptions opt = new ChromeOptions();
      opt.setCapability("webSocketUrl", true);

      // Initiate the Webdriver
      WebDriver driver = new ChromeDriver(opt);

      // adding implicit wait of 15 secs
      driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);

      // launching a browser and open a URL
      driver.get("https://tutorialspoint.tw/selenium/practice/check-box.php");

      // open browsing context in new tab
      BrowsingContext bc1 = new BrowsingContext(driver, WindowType.TAB);

      // open another browsing context in new tab
      BrowsingContext bc2 = new BrowsingContext(driver, WindowType.TAB);

      // list of every top level browsing contexts
      List<BrowsingContextInfo> tree = bc1.getTopLevelContexts();

      // obtain total browsing context tree
      int size = tree.size();
      System.out.println("Total top level browsing context before closing: " + size);

      // close one browsing context
      bc2.close();

      // obtain total browsing context tree after closing one
      List<BrowsingContextInfo> tree1 = bc1.getTopLevelContexts();
      int size1 = tree1.size();
      System.out.println("Total top level browsing context after closing: " + size1);

      // Quitting browser
      driver.quit();
   }
}

它將顯示以下 **輸出**:

Total top level browsing context before closing: 3
Total top level browsing context after closing: 2

Process finished with exit code 0

啟用瀏覽器上下文

讓我們來看一個例子,我們將使用 activate() 方法啟用瀏覽器上下文。

**BrowsingContextTabClose.java** 中的程式碼實現

package org.example;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WindowType;
import org.openqa.selenium.bidi.browsingcontext.BrowsingContext;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import java.util.concurrent.TimeUnit;

public class BrowsingContextTabClose {
   public static void main(String[] args) throws InterruptedException {

      // object of ChromeOptions
      ChromeOptions opt = new ChromeOptions();
      opt.setCapability("webSocketUrl", true);

      // Initiate the Webdriver
      WebDriver driver = new ChromeDriver(opt);

      // adding implicit wait of 15 secs
      driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);

      // launching a browser and open a URL
      driver.get("https://tutorialspoint.tw/selenium/practice/check-box.php");

      // get window handle id
      String windowID = driver.getWindowHandle();

      // open browsing context
      BrowsingContext bc1 = new BrowsingContext(driver, windowID);

      // open another browsing context in new window
      BrowsingContext bc2 = new BrowsingContext(driver, WindowType.WINDOW);

      // activate browsing context
      bc1.activate();

      // Quitting browser
      driver.quit();
   }
}

重新載入瀏覽器上下文

讓我們來看一個例子,我們將重新載入瀏覽器上下文並獲取導航 ID 和 URL。

**BrowsingContextReload.java** 中的程式碼實現

package org.example;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WindowType;
import org.openqa.selenium.bidi.browsingcontext.BrowsingContext;
import org.openqa.selenium.bidi.browsingcontext.NavigationResult;
import org.openqa.selenium.bidi.browsingcontext.ReadinessState;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import java.util.concurrent.TimeUnit;

public class BrowsingContextReload {
   public static void main(String[] args) throws InterruptedException {

      // object of ChromeOptions
      ChromeOptions opt = new ChromeOptions();
      opt.setCapability("webSocketUrl", true);

      // Initiate the Webdriver
      WebDriver driver = new ChromeDriver(opt);

      // adding implicit wait of 15 secs
      driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);

      // launching a browser and open a URL
      driver.get("https://tutorialspoint.tw/selenium/practice/check-box.php");

      // open browsing context in new tab
      BrowsingContext bc = new BrowsingContext(driver, WindowType.TAB);

      // navigate to URL in a browsing context
      bc.navigate("https://tutorialspoint.tw/selenium/practice/buttons.php", ReadinessState.COMPLETE);

      // reload browsing context
      NavigationResult load = bc.reload(ReadinessState.INTERACTIVE);

      // get navigation id
      String text = load.getNavigationId();
      System.out.println("Navigation ID: " + text);

      // get URL opened in browsing context
      String url = load.getUrl();
      System.out.println("Navigation URL: " + url);

      // Quitting browser
      driver.quit();
   }
}

它將顯示以下 **輸出**:

Navigation ID: 0C12BD5C26E08392DB18F6C7928F8020
Navigation URL: 
https://tutorialspoint.tw/selenium/practice/buttons.php

Process finished with exit code 0

在上面的示例中,我們重新載入了瀏覽器上下文,並在控制檯中獲得了導航 ID 和 URL,訊息為 - **導航 ID:0C12BD5C26E08392DB18F6C7928F8020** 和 **導航 URL:** https://tutorialspoint.tw/selenium/

最後,收到訊息 **程序已完成,退出程式碼為 0**,表示程式碼已成功執行。

使用瀏覽上下文處理使用者提示

讓我們來看一個使用handleUserPrompt()方法透過瀏覽上下文處理使用者提示的例子。

程式碼實現位於BrowsingContextHandlePrompt.java

package org.example;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.bidi.browsingcontext.BrowsingContext;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import java.util.concurrent.TimeUnit;

public class BrowsingContextHandlePrompt {
   public static void main(String[] args) throws InterruptedException {

      // object of ChromeOptions
      ChromeOptions opt = new ChromeOptions();
      opt.setCapability("webSocketUrl", true);

      // Initiate the Webdriver
      WebDriver driver = new ChromeDriver(opt);

      // adding implicit wait of 15 secs
      driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);

      // launching a browser and open a URL
      driver.get("https://tutorialspoint.tw/selenium/practice/alerts.php");

      // get window handle
      String windowID = driver.getWindowHandle();

      // open browsing context
      BrowsingContext bc = new BrowsingContext(driver, driver.getWindowHandle());

      // identify button
      WebElement btn = driver.findElement(By.xpath("/html/body/main/div/div/div[2]/div[1]/button"));
      btn.click();

      // accept and input text in prompt
      bc.handleUserPrompt(true, "Tutorialspoint");

      // Quitting browser
      driver.quit();
   }
}

它將顯示以下 **輸出**:

Process finished with exit code 0

在上面的例子中,我們已經使用瀏覽上下文處理了使用者提示。

最後,收到訊息 **程序已完成,退出程式碼為 0**,表示程式碼已成功執行。

使用瀏覽上下文捕獲螢幕截圖

讓我們來看一個使用captureScreenshot()方法透過瀏覽上下文捕獲螢幕截圖的例子。

程式碼實現位於BrowsingContextCaptureScreenshot.java

package org.example;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.bidi.browsingcontext.BrowsingContext;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import java.util.concurrent.TimeUnit;

public class BrowsingContextCaptureScreenshot {
   public static void main(String[] args) throws InterruptedException {

      // object of ChromeOptions
      ChromeOptions opt = new ChromeOptions();
      opt.setCapability("webSocketUrl", true);

      // Initiate the Webdriver
      WebDriver driver = new ChromeDriver(opt);

      // adding implicit wait of 15 secs
      driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);

      // launching a browser and open a URL
      driver.get("https://tutorialspoint.tw/selenium/practice/alerts.php");

      // get window handle
      String windowID = driver.getWindowHandle();

      // open browsing context
      BrowsingContext bc = new BrowsingContext(driver, driver.getWindowHandle());

      // identify button then click
      WebElement btn = driver.findElement(By.xpath("/html/body/main/div/div/div[2]/div[1]/button"));
      btn.click();

      // capture screenshot
      String sc = bc.captureScreenshot();

      // get number of screenshot
      int size = sc.length();
      System.out.println("Size of Screenshot: " + size);

      // Quitting browser
      driver.quit();
   }
}

它將顯示以下 **輸出**:

Size of Screenshots: 209152

Process finished with exit code 0

使用瀏覽上下文捕獲元素的螢幕截圖

讓我們來看一個使用captureElementScreenshot()方法透過瀏覽上下文捕獲元素螢幕截圖的例子。

程式碼實現位於BrowsingContextElemntCaptureScreenshot.java

package org.example;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.bidi.browsingcontext.BrowsingContext;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.remote.RemoteWebElement;
import java.util.concurrent.TimeUnit;

public class BrowsingContextElemntCaptureScreenshot {
   public static void main(String[] args) throws InterruptedException {

      // object of ChromeOptions
      ChromeOptions opt = new ChromeOptions();
      opt.setCapability("webSocketUrl", true);

      // Initiate the Webdriver
      WebDriver driver = new ChromeDriver(opt);

      // adding implicit wait of 15 secs
      driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);

      // get window handle
      String windowID = driver.getWindowHandle();

      // open browsing context
      BrowsingContext bc = new BrowsingContext(driver, windowID);

      // launching a browser and open a URL
      driver.get("https://tutorialspoint.tw/selenium/practice/alerts.php");

      // identify button
      WebElement btn = driver.findElement(By.xpath("/html/body/main/div/div/div[2]/div[1]/button"));

      String sc = bc.captureElementScreenshot(((RemoteWebElement) btn).getId());

      // get number of screenshot
      int size = sc.length();
      System.out.println("Size of Screenshot of an element: " + size);

      // Quitting browser
      driver.quit();
   }
}

它將顯示以下 **輸出**:

Size of Screenshot of an element: 3080

Process finished with exit code 0

使用瀏覽上下文設定視口畫素

讓我們來看一個使用setViewport()方法透過瀏覽上下文設定視口畫素的例子。

程式碼實現位於SetViewPort.java

package org.example;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.bidi.browsingcontext.BrowsingContext;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import java.util.concurrent.TimeUnit;

public class SetViewPort {
   public static void main(String[] args) throws InterruptedException {

      // object of ChromeOptions
      ChromeOptions opt = new ChromeOptions();
      opt.setCapability("webSocketUrl", true);

      // Initiate the Webdriver
      WebDriver driver = new ChromeDriver(opt);

      // adding implicit wait of 15 secs
      driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);

      // get window handle
      String windowID = driver.getWindowHandle();

      // open browsing context
      BrowsingContext bc = new BrowsingContext(driver, windowID);

      // launching a browser and open a URL
      driver.get("https://tutorialspoint.tw/selenium/practice/alerts.php");

      // set view port
      bc.setViewport(200, 600, 6);

      // Quitting browser
      driver.quit();
   }
}

它將顯示以下 **輸出**:

Process finished with exit code 0

使用瀏覽上下文列印頁面

讓我們來看一個使用print()方法透過瀏覽上下文列印頁面的例子。

程式碼實現位於PrintPage.java

package org.example;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.bidi.browsingcontext.BrowsingContext;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.print.PrintOptions;
import java.util.concurrent.TimeUnit;

public class PrintPage {
   public static void main(String[] args) throws InterruptedException {

      // object of ChromeOptions
      ChromeOptions opt = new ChromeOptions();
      opt.setCapability("webSocketUrl", true);

      // Initiate the Webdriver
      WebDriver driver = new ChromeDriver(opt);

      // adding implicit wait of 15 secs
      driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);

      // get window handle
      String windowID = driver.getWindowHandle();

      // open browsing context
      BrowsingContext bc = new BrowsingContext(driver, windowID);

      // launching a browser and open a URL
      driver.get("https://tutorialspoint.tw/selenium/practice/alerts.php");

      // object of PrintOptions
      PrintOptions p = new PrintOptions();

      // get print
      String print = bc.print(p);

      // Quitting browser
      driver.quit();
   }
}

使用瀏覽上下文在瀏覽器歷史記錄中導航、前進、後退和遍歷

讓我們來看一個使用瀏覽上下文在瀏覽器歷史記錄中前進、後退和遍歷的例子。這些操作是使用BrowsingContext類的forward()、back()和traverse(-1)方法執行的。

程式碼實現位於BrowsingContextHistory.java

package org.example;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.bidi.browsingcontext.BrowsingContext;
import org.openqa.selenium.bidi.browsingcontext.ReadinessState;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import java.util.concurrent.TimeUnit;

public class BrowsingContextHistory {
   public static void main(String[] args) throws InterruptedException {

      // object of ChromeOptions
      ChromeOptions opt = new ChromeOptions();
      opt.setCapability("webSocketUrl", true);

      // Initiate the Webdriver
      WebDriver driver = new ChromeDriver(opt);

      // adding implicit wait of 15 secs
      driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);

      // get window handle
      String windowID = driver.getWindowHandle();

      // open browsing context
      BrowsingContext bc = new BrowsingContext(driver, windowID);

      // navigate to URL
      bc.navigate("https://tutorialspoint.tw/selenium/practice/login.php", ReadinessState.COMPLETE);

      // identify element then click
      WebElement btn = driver.findElement(By.xpath("//*[@id='signInForm']/div[3]/a"));
      btn.click();

      // get page title after click
      String title = driver.getTitle();
      System.out.println("Page title after click: " + title);

      // navigate back in browser history
      bc.back();

      // get page title after navigating back in browser history
      String title1 = driver.getTitle();
      System.out.println("Page title after navigating back in browser history: " + title1);

      // navigate forward in browser history
      bc.forward();

      // get page title after navigating forward in browser history
      String title2 = driver.getTitle();
      System.out.println("Page title after navigating forward in browser history: " + title2);


      // traverse history
      bc.traverseHistory(-1);

      // Quitting browser
      driver.quit();
   }
}

它將顯示以下 **輸出**:

Page title after click: Selenium Practice - Register
Page title after navigating back in browser history: Selenium Practice - Login
Page title after navigating forward in browser history: Selenium Practice - Register

Process finished with exit code 0

在上面的例子中,我們啟動了一個應用程式,並在瀏覽器歷史記錄中進行了後退和前進導航,並在控制檯中獲取了導航後的瀏覽器標題,訊息為:點選後頁面標題:Selenium Practice - Register,瀏覽器歷史記錄後退後頁面標題:Selenium Practice - Login,以及瀏覽器歷史記錄前進後頁面標題:Selenium Practice - Register

本教程到此結束,我們全面介紹了Selenium WebDriver - 瀏覽器上下文。我們首先描述了什麼是瀏覽器上下文以及瀏覽器上下文所需的Selenium依賴項,然後逐步講解了在新的視窗和標籤頁中建立瀏覽器上下文、使用現有視窗控制代碼在新的視窗和標籤頁中建立瀏覽器上下文、在正常狀態和就緒狀態下導航到URL、獲取瀏覽器上下文樹、其深度和所有頂級瀏覽器上下文、關閉標籤頁或視窗、啟用和重新載入瀏覽器上下文、處理使用者提示、捕獲網頁和特定元素的螢幕截圖、設定視口畫素、列印頁面以及使用Selenium在瀏覽器歷史記錄中前進、後退和遍歷的示例。

這使您具備了Selenium WebDriver - 瀏覽器上下文的深入知識。最好繼續練習您學到的知識,並探索與Selenium相關的其他知識,以加深您的理解並拓寬您的視野。

廣告