
- Selenium 教程
- Selenium - 首頁
- Selenium - 概述
- Selenium - 元件
- Selenium - 自動化測試
- Selenium - 環境搭建
- Selenium - 遠端控制
- Selenium IDE 教程
- Selenium - IDE 簡介
- Selenium - 特性
- Selenium - 限制
- Selenium - 安裝
- Selenium - 建立測試
- Selenium - 建立指令碼
- Selenium - 控制流
- Selenium - 儲存變數
- Selenium - 警報和彈出視窗
- Selenium - Selenese 命令
- Selenium - Actions 命令
- Selenium - Accessors 命令
- Selenium - Assertions 命令
- Selenium - Assert/Verify 方法
- Selenium - 定位策略
- Selenium - 指令碼除錯
- Selenium - 驗證點
- Selenium - 模式匹配
- Selenium - JSON 資料檔案
- Selenium - 瀏覽器執行
- Selenium - 使用者擴充套件
- Selenium - 程式碼匯出
- Selenium - 程式碼輸出
- Selenium - JavaScript 函式
- Selenium - 外掛
- Selenium WebDriver 教程
- Selenium - 簡介
- Selenium WebDriver vs RC
- Selenium - 安裝
- Selenium - 第一個測試指令碼
- Selenium - 驅動程式會話
- Selenium - 瀏覽器選項
- Selenium - Chrome 選項
- Selenium - Edge 選項
- Selenium - Firefox 選項
- Selenium - Safari 選項
- Selenium - 雙擊
- Selenium - 右鍵單擊
- Python 中的 HTML 報告
- 處理編輯框
- Selenium - 單個元素
- Selenium - 多個元素
- Selenium Web 元素
- Selenium - 檔案上傳
- Selenium - 定位器策略
- Selenium - 相對定位器
- Selenium - 定位器
- Selenium - 查詢所有連結
- Selenium - 使用者互動
- Selenium - WebElement 命令
- Selenium - 瀏覽器互動
- Selenium - 瀏覽器命令
- Selenium - 瀏覽器導航
- Selenium - 警報和彈出視窗
- Selenium - 處理表單
- Selenium - 視窗和選項卡
- Selenium - 處理連結
- Selenium - 輸入框
- Selenium - 單選按鈕
- Selenium - 複選框
- Selenium - 下拉框
- Selenium - 處理 IFrame
- Selenium - 處理 Cookie
- Selenium - 日期時間選擇器
- Selenium - 動態 Web 表格
- Selenium - Actions 類
- Selenium - Action 類
- Selenium - 鍵盤事件
- Selenium - 鍵上/下
- Selenium - 複製和貼上
- Selenium - 處理特殊鍵
- Selenium - 滑鼠事件
- Selenium - 拖放
- Selenium - 筆事件
- Selenium - 滾動操作
- Selenium - 等待策略
- Selenium - 顯式/隱式等待
- Selenium - 支援功能
- Selenium - 多選
- Selenium - 等待支援
- Selenium - 選擇支援
- Selenium - 顏色支援
- Selenium - ThreadGuard
- Selenium - 錯誤和日誌記錄
- Selenium - 異常處理
- Selenium - 雜項
- Selenium - 處理 Ajax 呼叫
- Selenium - JSON 資料檔案
- Selenium - CSV 資料檔案
- Selenium - Excel 資料檔案
- Selenium - 跨瀏覽器測試
- Selenium - 多瀏覽器測試
- Selenium - 多視窗測試
- Selenium - JavaScript 執行器
- Selenium - 無頭執行
- Selenium - 捕獲螢幕截圖
- Selenium - 捕獲影片
- Selenium - 頁面物件模型
- Selenium - 頁面工廠
- Selenium - 記錄和回放
- Selenium - 框架
- Selenium - 瀏覽上下文
- Selenium - DevTools
- Selenium Grid 教程
- Selenium - 概述
- Selenium - 架構
- Selenium - 元件
- Selenium - 配置
- Selenium - 建立測試指令碼
- Selenium - 測試執行
- Selenium - 端點
- Selenium - 自定義節點
- Selenium 報告工具
- Selenium - 報告工具
- Selenium - TestNG
- Selenium - JUnit
- Selenium - Allure
- Selenium & 其他技術
- Selenium - Java 教程
- Selenium - Python 教程
- Selenium - C# 教程
- Selenium - Javascript 教程
- Selenium - Kotlin 教程
- Selenium - Ruby 教程
- Selenium - Maven & Jenkins
- Selenium - 資料庫測試
- Selenium - LogExpert 日誌記錄
- Selenium - Log4j 日誌記錄
- Selenium - Robot Framework
- Selenium - AutoIT
- Selenium - Flash 測試
- Selenium - Apache Ant
- Selenium - Github 教程
- Selenium - SoapUI
- Selenium - Cucumber
- Selenium - IntelliJ
- Selenium - XPath
Selenium WebDriver - 定位器
Selenium Webdriver 可以用來定位具有相同匹配定位器值的元素。在網頁上,如果多個元素具有相同的定位器值,則僅獲取第一個匹配元素(從頁面右上角開始)的引用。
findElement 方法
findElement() 方法返回 DOM 中第一個具有相同定位器值的元素。如果有多個元素具有相同的定位器值,我們可以使用 id 定位器識別單個元素,因為它始終唯一地標識網頁上的一個元素。
使用巢狀 findElement 識別元素
讓我們以下面圖片中突出顯示的 HTML 程式碼片段為例,其中包含與 li 標記名稱相同的元素。讓我們識別第一個 li 元素(其父元素的標記名稱為 ul)具有子元素連結(標記名稱為“a”)為 文字框 -

為了獲取該元素,我們首先唯一地識別了作為搜尋元素的祖先而不是不需要的元素的祖先的元素,然後在該物件上應用了 findElement() 方法。
我們可以使用 findElements() 方法獲取所有具有相同定位器值的匹配元素。這將返回一個匹配元素列表。如果不存在匹配元素,我們將獲得一個大小為 0 的列表。
帶巢狀命令的語法 -
WebDriver driver = new ChromeDriver(); // identify all elements under tagname ul WebElement elements = driver.findElement(By.id("navMenus")); // identify first li element under ul then click WebElement element = elements.findElement(By.xpath("//li[1]/a"));
示例 1
讓我們單擊 文字框 連結,並在網頁上獲取文字 文字框。

程式碼實現
package org.example; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import java.util.concurrent.TimeUnit; public class Finders { public static void main(String[] args) throws InterruptedException { // Initiate the Webdriver WebDriver driver = new ChromeDriver(); // adding implicit wait of 15 secs driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS); // Opening the webpage driver.get("https://tutorialspoint.tw/selenium/practice/selenium_automation_practice.php"); // identify element then click WebElement l = driver.findElement(By.xpath("//*[@id='headingOne']/button")); l.click(); // identify all elements under tagname ul WebElement elements = driver.findElement(By.id("navMenus")); // identify first li element under ul then click WebElement element = elements.findElement(By.xpath("//li[1]/a")); element.click(); WebElement e = driver.findElement(By.xpath("//*[@id='TextForm']/h1")); System.out.println("Text is: " + e.getText()); // Closing browser driver.quit(); } }
輸出
Text is: Text Box
在上面的示例中,我們首先使用巢狀定位器識別了元素,然後在控制檯中獲取帶有訊息的文字:文字是:文字框。
最後,收到訊息 程序已完成,退出程式碼為 0,表示程式碼已成功執行。
但是,我們可以使用最佳化的技術來使用 xpath 或 css 定位器識別該元素,因為從效能方面考慮,巢狀方法並不好。
語法
WebDriver driver = new ChromeDriver(); // identify element with xpath WebElement element = driver.findElement(By.xpath("//*[@id='navMenus']/li[1]/a"));
示例 2
package org.example; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import java.util.concurrent.TimeUnit; public class Finder { public static void main(String[] args) throws InterruptedException { // Initiate the Webdriver WebDriver driver = new ChromeDriver(); // adding implicit wait of 15 secs driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS); // Opening the webpage driver.get("https://tutorialspoint.tw/selenium/practice/selenium_automation_practice.php"); // identify element then click WebElement l = driver.findElement(By.xpath("//*[@id='headingOne']/button")); l.click(); // identify element with xpath WebElement element = driver.findElement(By.xpath("//*[@id='navMenus']/li[1]/a")); element.click(); WebElement e = driver.findElement(By.xpath("//*[@id='TextForm']/h1")); System.out.println("Text is: " + e.getText()); // Closing browser driver.quit(); } }
輸出
Text is: Text Box
在上面的示例中,我們首先使用 xpath 定位器識別了元素,然後在控制檯中獲取帶有訊息的文字:文字是:文字框。
使用 findElements 方法識別連結
連結由錨標記名稱與稱為 href 的屬性識別。
現在讓我們討論一下下面圖片中顯示的網頁上鍊接 錯誤請求 的識別。首先,右鍵單擊頁面,然後在 Chrome 瀏覽器中單擊“檢查”按鈕。然後,將顯示整個頁面的相應 HTML 程式碼。要檢查頁面上的連結,請單擊位於 HTML 程式碼頂部的左側向上箭頭,如下所示。

一旦我們單擊並指向箭頭指向“錯誤請求”超連結,其 HTML 程式碼就會可見,反映了錨標記名稱(稱為“a”並用 <> 括起來)和 href 屬性。

讓我們以上面頁面的示例為例,我們首先使用 findElements() 方法計算連結的總數,然後單擊特定的連結,例如 錯誤請求。單擊該連結後,我們將收到訊息 連結已使用狀態 400 和狀態文字錯誤請求進行響應。

語法
WebDriver driver = new ChromeDriver(); List<WebElement> totalLnks = driver.findElements(By.tagName("a") );
示例
package org.example; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import java.util.List; import java.util.concurrent.TimeUnit; import org.openqa.selenium.By; import org.openqa.selenium.WebElement; public class TotalLnks { public static void main(String[] args) throws InterruptedException { // Initiate the Webdriver WebDriver driver = new ChromeDriver() ; // adding implicit wait of 10 secs driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); // Opening the webpage where we will count the links driver.get("https://tutorialspoint.tw/selenium/practice/links.php" ) ; // Retrieve all links using locator By.tagName and storing in List List<WebElement> totalLnks = driver.findElements(By.tagName("a") ); System.out.println( "Total number of links: " + totalLnks.size() ) ; // Running loop through list of web elements for( int j = 0; j < totalLnks.size(); j ++){ if( totalLnks.get(j).getText().equalsIgnoreCase("Bad Request") ) { totalLnks.get(j).click() ; break ; } } // get text WebElement t = driver.findElement (By.xpath("/html/body/main/div/div/div[2]/div[4]")); System.out.println("Text is: " + t.getText()); // Closing browser driver.quit(); } }
輸出
Total number of links: 42 Text is: Link has responded with status 400 and status text Bad Request
在上面的示例中,我們計算了網頁上的連結總數,並在控制檯中收到了訊息 - 連結總數:42,然後在執行單擊後獲取生成的文字,並顯示訊息 - 文字是:連結已使用狀態 400 和狀態文字錯誤請求進行響應。
findElements 方法無匹配元素
讓我們舉一個例子並實現一個程式碼,在該程式碼中我們將看到 findElements() 方法返回的列表可能包含 0 個元素,如果使用給定定位器值沒有 0 個元素。
示例
package org.example; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import java.util.List; import java.util.concurrent.TimeUnit; public class FindElement { public static void main(String[] args) throws InterruptedException { // Initiate the Webdriver WebDriver driver = new ChromeDriver(); // adding implicit wait of 15 secs driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS); // Opening the webpage where we will identify element driver.get("https://tutorialspoint.tw/selenium/practice/links.php"); // Retrieve all elements using By.class name ul and storing in List List<WebElement> total = driver.findElements(By.tagName("input")); System.out.println( "Total number of elements with tagname input: " + total.size() ) ; //Closing browser driver.quit(); } }
輸出
Total number of elements with tagname input: 0
在上面的示例中,我們計算了所有具有標記名稱為 input 的元素,並在控制檯中收到了訊息 - 具有標記名稱 input 的元素總數:0(因為沒有匹配的元素)。
findElement 方法無匹配元素
讓我們舉一個例子並實現一個程式碼,在該程式碼中我們將收到 findElement() 方法返回的 NoSuchElement 異常,如果使用給定定位器值沒有 0 個元素。
示例
package org.example; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import java.util.concurrent.TimeUnit; public class FindElementWithException { public static void main(String[] args) throws InterruptedException { // Initiate the Webdriver WebDriver driver = new ChromeDriver(); // adding implicit wait of 15 secs driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS); // Opening the webpage where we will identify element driver.get("https://tutorialspoint.tw/selenium/practice/links.php"); // Retrieve element using By.class name ul WebElement e = driver.findElement(By.className("ul")); System.out.println( "Element is : " + e); // Closing browser driver.quit(); } }
輸出
Exception in thread "main" org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"css selector","selector":".ul"} (Session info: chrome=121.0.6167.160) For documentation on this error, please visit: https://www.selenium.dev/documentation/webdriver/troubleshooting/errors#no-such-element-exception Process finished with exit code 1
在上面的示例中,我們收到了 程序已完成,退出程式碼為 1,表示程式碼執行失敗。此外,我們還獲得了 NoSuchElementException(因為網頁上沒有元素具有匹配的定位器值)。
findElements 和 findElement 方法的區別
因此,findElement() 和 findElements() 之間的基本區別如下所示 -
findElement() 方法返回一個 Web 元素,而 findElements() 方法返回 Web 元素列表。
如果不存在匹配元素,則 findElement() 方法將丟擲 NoSuchElementException,而 findElements() 方法將返回一個大小為 0 的列表。
activeElement 方法
在網頁上的所有元素中,我們可以使用 activeElement() 方法獲取獲得焦點的元素。
讓我們以上面頁面的示例為例,我們首先使用 sendKeys() 方法在輸入框中輸入文字 Selenium。然後使用 activeElement() 方法獲取焦點元素的屬性(在將驅動程式的上下文切換到焦點元素後完成)。

示例
package org.example; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import java.util.concurrent.TimeUnit; public class HandlingActivesElement { public static void main(String[] args) throws InterruptedException { // Initiate the Webdriver WebDriver driver = new ChromeDriver(); // adding implicit wait of 15 secs driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS); // launching URL driver.get("https://tutorialspoint.tw/selenium/practice/text-box.php"); // Identify the input box with xpath locator WebElement e = driver.findElement(By.xpath("//*[@id='fullname']")); // enter text in input box e.sendKeys("Selenium"); // Get the value of element in focus after switching driver context String a = driver.switchTo().activeElement().getAttribute("value"); System.out.println("Value entered: " + a); // Closing browser driver.quit(); } }
輸出
Value entered: Selenium
在上面的示例中,我們首先在輸入框中輸入了文字 Selenium,並在控制檯中檢索了當前焦點元素的值,並顯示訊息 - 輸入的值:Selenium(即輸入的值)。
結論
這總結了我們對 Selenium Webdriver 定位器教程的全面介紹。我們首先介紹了 findElement 方法、使用巢狀 findElement 識別元素、使用 findElements 方法識別連結、findElements 方法無匹配元素、findElement 方法無匹配元素、findElements 和 findElement 方法的區別、activeElement 方法以及說明如何在 Selenium Webdriver 中使用定位器的示例。這使您對 Selenium Webdriver 定位器有了深入的瞭解。明智的做法是不斷練習您學到的知識,並探索與 Selenium 相關的其他知識,以加深您的理解並擴充套件您的視野。