创建 CSS 表达式有哪些不同的方法?

cssfront end technologyprogramming更新于 2026/1/27 20:28:17

创建 CSS 表达式的不同方法如下 −

  • 使用类作为 CSS 选择器

    这将选择该特定类的所有 Web 元素。(例如,用 (.) 表示 - .classname)

  • 使用 ID 作为 CSS 选择器。

    这将选择该特定 ID 的 Web 元素。(例如,用 (#) 表示 - #ID)

  • 使用标签名和属性值作为选择器。

    这将选择该特定属性值组合的 Web 元素。(例如,用标签名 [attribute=’value’] 表示)

示例

import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
public class CssExpression {
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver", "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      String url = "https://www.tutorialspoint.com/index.htm";
      driver.get(url);
      driver.manage().timeouts().implicitlyWait(12, TimeUnit.SECONDS);
      //使用 class 和 . 作为 css 表达式
      driver.findElement(By.cssSelector(".gsc- input")).sendKeys("Selenium");
      driver.close();
      }
}

示例

import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
public class CssId {
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver",    "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      String url = "https://www.tutorialspoint.com/index.htm";
      driver.get(url);
      driver.manage().timeouts().implicitlyWait(12, TimeUnit.SECONDS);
      //使用带有#的id作为css表达式
      driver.findElement(By.cssSelector("#gsc-i- id1")).sendKeys("Selenium");
      driver.close();
   }
}

示例

import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
public class CssTagExp {
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver", "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      String url = "https://www.tutorialspoint.com/index.htm";
      driver.get(url);
      driver.manage().timeouts().implicitlyWait(12, TimeUnit.SECONDS);
      //使用id标签名属性组合进行css表达
      driver.findElement(By.cssSelector("input[name=’search’]")).
      sendKeys("Selenium");
      driver.close();
   }
}

有用资源