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.com/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();
}
}输出

数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP