• Selenium Video Tutorials

Selenium WebDriver - 定位策略



啟動應用程式後,使用者會與頁面上的元素進行互動,例如單擊連結/按鈕、在輸入框中鍵入文字、從下拉列表中選擇選項等等,以建立自動化測試用例。第一步是使用其屬性識別元素。可以使用定位器(例如 id、name、class name、xpath、css、tagname、link text 和 partial link)進行此識別。

Id 定位器

元素的 id 屬性可用於識別它。在 Java 中,方法 findElement(By.id("<id 屬性的值>")) 用於查詢具有 id 屬性值的元素。使用此方法,應識別第一個與 id 屬性值匹配的元素。如果不存在 id 屬性值相同的元素,則會丟擲 NoSuchElementException。

語法

Webdriver driver = new ChromeDriver();
driver.findElement(By.id("id value”)); 

讓我們看一下下面圖片中突出顯示的姓名旁邊的輸入框的 html 程式碼:

Selenium Locator Strategies 1

上圖中突出顯示的編輯框具有一個 id 屬性,其值為name。讓我們嘗試在此編輯框中輸入文字Selenium

示例

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 LocatorID {
   public static void main(String[] args) throws InterruptedException {

      // Initiate the Webdriver
      WebDriver driver = new ChromeDriver();
      
      // adding implicit wait of 20 secs
      driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
      
      // Opening the webpage where we will identify edit box enter text
      driver.get("https://tutorialspoint.tw/selenium/practice/selenium_automation_practice.php");
      
      // Identify the search box with id locator then enter text Selenium
      WebElement i = driver.findElement(By.id("name"));
      i.sendKeys("Selenium");
      
      // Get the value entered
      String text = i.getAttribute("value");
      System.out.println("Entered text is: " + text);
      
      // Close browser
      driver.quit();
   }
}

它將顯示以下輸出:

Entered text is: Selenium

Process finished with exit code 0

輸出顯示訊息 - 程序退出程式碼為 0,表示上述程式碼已成功執行。此外,在控制檯中接收到了在編輯框中輸入的值(從 getAttribute 方法獲得) - Selenium

Name 定位器

元素的 name 屬性可用於識別它。在 Java 中,方法 findElement(By.name("<name 屬性的值>")) 用於查詢具有 name 屬性值的元素。使用此方法,應識別第一個與 name 屬性值匹配的元素。如果不存在 name 屬性值相同的元素,則會丟擲 NoSuchElementException。

語法

Webdriver driver = new ChromeDriver();
driver.findElement(By.name("name value"));

讓我們研究一下下面圖片中與之前討論的相同輸入框的 html 程式碼:

Selenium Locator Strategies 2

上圖中突出顯示的編輯框具有一個 name 屬性,其值為name。讓我們在此編輯框中輸入文字Selenium

示例

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 LocatorName {
   public static void main(String[] args) throws InterruptedException {
   
      // Initiate the Webdriver
      WebDriver driver = new ChromeDriver();
      
      // adding implicit wait of 20 secs
      driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);

      // Opening the webpage where we will identify edit box enter text
      driver.get("https://tutorialspoint.tw/selenium/practice/selenium_automation_practice.php");

      // Identify the search box with name locator to enter text
      WebElement i = driver.findElement(By.name("name"));
      i.sendKeys("Selenium");
      
      // Get the value entered
      String text = i.getAttribute("value");
      System.out.println("Entered text is: " + text);
      
      // Close browser
      driver.quit();
   }
}

它將顯示以下輸出:

Entered text is: Selenium 

在控制檯中列印了編輯框中輸入的值 - Selenium

Class Name 定位器

元素的 class name 屬性可用於識別它。在 Java 中,方法 findElement(By.className("<class name 屬性的值>")) 用於查詢具有 class name 屬性值的元素。使用此方法,應識別第一個與 class name 屬性值匹配的元素。如果不存在 name 屬性值相同的元素,則會丟擲 NoSuchElementException。

語法

Webdriver driver = new ChromeDriver();
driver.findElement(By.className("class name value")); 

讓我們看一下下面圖片中突出顯示的點選我的 html 程式碼:

Selenium Locator Strategies 3

它具有一個 class name 屬性,其值為btn-primary。單擊該元素後,我們將在頁面上獲得您已執行動態點選

Selenium Locator Strategies 4

示例

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 LocatorClassName {
   public static void main(String[] args) throws InterruptedException {
   
      // Initiate the Webdriver
      WebDriver driver = new ChromeDriver();
      
      // adding implicit wait of 20 secs
      driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
      
      // Opening the webpage where we will identify button to click
      driver.get("https://tutorialspoint.tw/selenium/practice/buttons.php");

      // Identify button with class name to click
      WebElement i = driver.findElement(By.className("btn-primary"));
      i.click();

      // Get text after click
      WebElement e = driver.findElement(By.xpath("//*[@id='welcomeDiv']"));
      String text = e.getText();
      System.out.println("Text is: " + text);
      
      // Closing browser
      driver.quit();
   }
}

它將顯示以下輸出:

Text is: You have done a dynamic click

我們在單擊點選我按鈕後在控制檯中獲得了文字,訊息為 - 文字為:您已執行動態點選

TagName 定位器

元素的 tagname 可用於識別它。在 Java 中,方法 findElement(By.tagName("<tagname 的值>")) 用於查詢具有 tagname 值的元素。使用此方法,應識別第一個與 tagname 值匹配的元素。如果不存在 tagname 值相同的元素,則會丟擲 NoSuchElementException。

語法

Webdriver driver = new ChromeDriver();
driver.findElement(By.tagName("tag name value"));

讓我們獲取下面圖片中文字姓名旁邊的輸入框的 html 程式碼:

Selenium Locator Strategies 5

上圖中突出顯示的輸入框的 tagname 為input。讓我們嘗試在該輸入框中輸入文字Java

示例

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 LocatorTagName {
   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);

      // launch a URL
      driver.get("https://tutorialspoint.tw/selenium/practice/selenium_automation_practice.php");

      // Identify input box with tagname locator
      WebElement t = driver.findElement(By.tagName("input"));

      // then enter text
      t.sendKeys("Java");

      // Get the value entered
      String text = t.getAttribute("value");
      System.out.println("Entered text is: " + text);
      
      // Closing browser
      driver.quit();
   }
}

它將顯示以下輸出:

Entered text is: Java

在控制檯中列印了編輯框中輸入的值Java

Link Text 定位器

連結的 link text 可用於識別它。在 Java 中,方法 findElement(By.linkText("<link text 的值>")) 用於查詢具有 link text 值的連結。使用此方法,應識別第一個與 link text 值匹配的元素。如果不存在 link text 值相同的元素,則會丟擲 NoSuchElementException。它主要用於在網頁上定位連結。

語法

Webdriver driver = new ChromeDriver();
driver.findElement(By.linkText("value of link text"));

讓我們看一下下面圖片中突出顯示的連結已建立的 html 程式碼:

Selenium Locator Strategies 6

它的 link text 值為已建立。單擊它後,我們將在頁面上獲得連結已響應,狀態為 201,狀態文字為已建立

Selenium Locator Strategies 7

示例

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 LocatorLinkText {
   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);

      // launch a URL
      driver.get("https://tutorialspoint.tw/selenium/practice/links.php");

      // Identify link with tagname link text
      WebElement t = driver.findElement(By.linkText("Created"));

      // then click
      t.click();

      // Get the text
      WebElement e = driver.findElement(By.xpath("/html/body/main/div/div/div[2]/div[1]"));
      String text = e.getText();
      System.out.println("Text is: " + text);
      
      // Close browser
      driver.quit();
   }
}

它將顯示以下輸出:

Text is: Link has responded with status 201 and status text Created

我們在單擊已建立連結後在控制檯中獲得了文字,訊息為 - 連結已響應,狀態為 201,狀態文字為已建立

Partial Link Text 定位器

連結的 partial link text 可用於識別它。在 Java 中,方法 findElement(By.partialLinkText(“<partial link text 的值>”)) 用於查詢具有 partial link text 值的連結。使用此方法,應識別第一個與 partial link text 值匹配的元素。如果不存在 partial link text 值相同的元素,則會丟擲 NoSuchElementException。它主要用於在網頁上定位連結。

語法

Webdriver driver = new ChromeDriver();
driver.findElement(By.partialLinkText("partial link text value"));

讓我們研究一下下面圖片中突出顯示的連結錯誤請求的 html 程式碼:

Selenium Locator Strategies 8

它的 link text 值為錯誤請求。單擊它後,我們將在頁面上獲得文字連結已響應,狀態為 400,狀態文字為錯誤請求

Selenium Locator Strategies 9

示例

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 LocatorPartialLinkText {
   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);

      // launch a URL
      driver.get("https://tutorialspoint.tw/selenium/practice/links.php");

      // Identify link with tagname partial link text
      WebElement t = driver.findElement(By.partialLinkText("Bad"));

      // then click
      t.click();

      // Get the text
      WebElement e = driver.findElement(By.xpath("/html/body/main/div/div/div[2]/div[4]"));
      String text = e.getText();
      System.out.println("Text is: " + text);
      
      // Closing browser
      driver.quit();
   }
}

它將顯示以下輸出:

Text is: Link has responded with status 400 and status text Bad Request

我們在單擊錯誤請求連結後在控制檯中獲得了文字,訊息為 - 連結已響應,狀態為 400,狀態文字為錯誤請求

CSS 定位器

元素的 css 定位器值可用於識別它。在 Java 中,方法 findElement(By.cssSelector("<css 選擇器的值>")) 用於查詢具有 css 選擇器值的元素。使用此方法,應識別第一個與 css 選擇器值匹配的元素。如果不存在 css 選擇器值相同的元素,則會丟擲 NoSuchElementException。

語法

Webdriver driver = new ChromeDriver();
driver.findElement(By.cssSelector("value of css selector"));

建立 CSS 表示式的規則

下面討論了建立 css 表示式的規則:

  • 要使用 css 識別元素,表示式應為 tagname[attribute='value']。
  • 我們還可以專門使用 id 屬性來建立 css 表示式。對於 id,css 表示式的格式應為 tagname#id。例如,input#txt [此處 input 是 tagname,txt 是 id 屬性的值]。
  • 對於 class,css 表示式的格式應為 tagname.class。例如,input.cls-txt [此處 input 是 tagname,cls-txt 是 class 屬性的值]。

  • 如果一個父元素有 n 個子元素,並且我們想要識別第 n 個子元素,那麼 CSS 表示式應該為 nth-of-type(n)。類似地,要識別最後一個子元素,CSS 表示式應為 ul.reading li:last-child。

對於值動態變化的屬性,我們可以使用 ^= 來定位屬性值以特定文字開頭的元素。例如,input[name^='qa'] 這裡,input 是標籤名,name 屬性的值以 qa 開頭。

對於值動態變化的屬性,我們可以使用 $= 來定位屬性值以特定文字結尾的元素。例如,input[class$='txt'] 這裡,input 是標籤名,class 屬性的值以 txt 結尾。

對於值動態變化的屬性,我們可以使用 *= 來定位屬性值包含特定子文字的元素。例如,input[name*='nam'] 這裡,input 是標籤名,name 屬性的值包含子文字 nam。

讓我們獲取如下所示 Name 標籤旁邊的輸入框的 HTML 程式碼:

Selenium Locator Strategies 10

上面圖片中高亮的編輯框有一個名為 name 的屬性,其值為 name,CSS 表示式應為 input[name='name']

XPath 定位器

元素的 XPath 定位器值可以用於識別該元素。在 Java 中,方法 findElement(By.xpath("<value of xpath>")) 用於定位具有 XPath 值的元素。使用此方法,可以識別具有匹配 XPath 值的第一個元素。如果不存在具有類似 XPath 值的元素,則會丟擲 NoSuchElementException 異常。

語法

Webdriver driver = new ChromeDriver();
driver.findElement(By.xpath("value of xpath”));

建立 XPath 表示式的規則

要使用 XPath 定位元素,表示式應為 //tagname[@attribute='value']。XPath 可以分為兩種型別:相對 XPath 和絕對 XPath。絕對 XPath 以 / 符號開頭,從根節點開始到要定位的元素。

例如:

/html/body/div[1]/div[2]/div[1]/input

相對 XPath 以 // 符號開頭,並且不從根節點開始。

例如:

//img[@alt='TutorialsPoint']

讓我們深入瞭解高亮連結 - Home 的 HTML 程式碼,從根節點開始。

Selenium Locator Strategies 11

此元素的絕對 XPath 為:

/html/body/main/div/div/div[2]/p[1]/a

元素 Home 的相對 XPath 為:

//a[@href='https://tutorialspoint.tw/index.htm']

XPath 函式

還有一些可用的函式可以幫助構建相對 xpath 表示式。

text()

它用於定位網頁上具有可見文字的元素。Home 連結的 XPath 表示式為:

//*[text()='Home']

starts-with()

它用於識別屬性值以特定文字開頭的元素。此函式通常用於屬性值在每次頁面載入時都會發生變化的情況。

讓我們研究連結 Moved 的 HTML 程式碼:

Selenium Locator Strategies 12

XPath 表示式為:

//a[starts-with(@id, 'mov')].

結論

本教程全面介紹了 Selenium WebDriver 定位策略。我們從描述 Id 定位器、Name 定位器、Class Name 定位器、TagName 定位器、Link Text 定位器、Partial Link Text 定位器、CSS 定位器、XPath 定位器開始,並提供了示例說明如何將它們與 Selenium 一起使用。這使您深入瞭解 Selenium WebDriver 定位策略。建議您不斷練習所學知識,並探索與 Selenium 相關的其他知識,以加深理解並拓寬視野。

廣告