• Selenium Video Tutorials

Selenium WebDriver - 定位器



Selenium Webdriver 可以用來定位具有相同匹配定位器值的元素。在網頁上,如果多個元素具有相同的定位器值,則僅獲取第一個匹配元素(從頁面右上角開始)的引用。

findElement 方法

findElement() 方法返回 DOM 中第一個具有相同定位器值的元素。如果有多個元素具有相同的定位器值,我們可以使用 id 定位器識別單個元素,因為它始終唯一地標識網頁上的一個元素。

使用巢狀 findElement 識別元素

讓我們以下面圖片中突出顯示的 HTML 程式碼片段為例,其中包含與 li 標記名稱相同的元素。讓我們識別第一個 li 元素(其父元素的標記名稱為 ul)具有子元素連結(標記名稱為“a”)為 文字框 -

Selenium Finders 1

為了獲取該元素,我們首先唯一地識別了作為搜尋元素的祖先而不是不需要的元素的祖先的元素,然後在該物件上應用了 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

讓我們單擊 文字框 連結,並在網頁上獲取文字 文字框

Selenium Finders 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 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 程式碼頂部的左側向上箭頭,如下所示。

Selenium Finders 3

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

Selenium Finders 4

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

Selenium Finders 5

語法

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() 方法獲取焦點元素的屬性(在將驅動程式的上下文切換到焦點元素後完成)。

Selenium Finders 6

示例

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 相關的其他知識,以加深您的理解並擴充套件您的視野。

廣告