Selenium 中 XPath 和 CSS 選擇器的主要區別是什麼?


XPath 和 CSS 選擇器之間存在一些差異。XPath 的格式為 //tagname[@attribute='value'],而 CSS 選擇器的格式為 tagname[attribute='value']。

我們可以使用 XPath 在 DOM 中向前和向後遍歷,即我們可以從父元素移動到子元素,也可以從子元素移動到父元素。但是對於 CSS,我們只能從父元素遍歷到子元素,反之則不行。

在效能方面,CSS 更好更快,而 XPath 則較慢。XPath 可以分為兩種型別 - 從根節點開始的絕對 XPath 和不需要從根節點開始的相對 XPath。

要遍歷到第 n 個元素,我們必須在 XPath 中提及 [n],其中 n 是索引號。對於 CSS,我們必須提及 nth-of-type(n)。例如,要獲取父元素 ul 的第二個 li 子元素,CSS 表示式應為 ul li:nth-of-type(2)。而 XPath 應為 ul/li[2]。

我們可以藉助元素上的可見文字使用 text() 函式建立 XPath,例如 //*[text()='Home'],它將識別頁面上顯示文字“Home”的元素。CSS 中沒有此功能。

XPath 中有 starts-with() 函式,用於識別其屬性值以特定文字開頭的元素。要處理 CSS 中的類似場景,我們必須使用 ^= 符號。

例如 在 CSS 中,

input[title^='qa']

例如 在 XPath 中,

//input[starts-with(@title, 'qa')].

[此處 input 是標籤名,title 屬性的值以 qa 開頭]。

XPath 中有 contains() 函式,用於識別其屬性值包含部分文字的元素。要處理 CSS 中的類似場景,我們使用 *= 符號

例如 在 CSS 中,

input[title*='nam']

例如 在 XPath 中,

//input[contains(@title, 'nam')].

[此處 input 是標籤名,title 屬性的值包含 nam]。

使用 id 屬性,CSS 表示式應為 tagname#id。例如,input#loc [此處 input 是標籤名,loc 是 id 屬性的值]。此規則不適用於 XPath。

使用 class 屬性,CSS 表示式應為 tagname.class 屬性值。例如,input.xt [此處 input 是標籤名,xt 是 class 屬性的值]。此規則不適用於 XPath。

語法

WebElement m = driver.findElement(By.xpath("//div[@class = 'loc']"));
WebElement n = driver.findElement(By.cssSelector("div[class = 'loc']"));

示例

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import java.util.concurrent.TimeUnit;
public class LocatorXpathvsCss{
   public static void main(String[] args) {
      System.setProperty("webdriver.gecko.driver",
         "C:\Users\ghs6kor\Desktop\Java\geckodriver.exe");
      WebDriver driver = new FirefoxDriver();
      //implicit wait
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      //URL launch
      driver.get("https://tutorialspoint.tw/online_dev_tools.htm");
      // identify element with xpath
      WebElement m=driver.findElement(By.xpath("//span[@class = 'cat-title']"));
      String str = m.getText();
      // identify element with css
      WebElement n=driver.
      findElement(By.cssSelector("div.cat-punch-line span"));
      String s = n.getText();
      System.out.println("Text obtained from xpath : " + str);
      System.out.println("Text obtained from css : " + s);
      driver.quit();
   }
}

輸出

更新於: 2021年4月6日

4K+ 瀏覽量

開啟你的 職業生涯

完成課程獲得認證

開始學習
廣告