Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> CSS

Các phương pháp tạo CSS Selector (biểu thức CSS) trong Selenium

Giới thiệu

CSS Selector là một trong những định vị (locator) mạnh mẽ, nhanh chóng và linh hoạt nhất trong Selenium WebDriver. Bài viết tổng hợp 3 phương pháp phổ biến nhất để xây dựng CSS Selector chính xác.

3 Phương pháp chính

1. Sử dụng Class Selector (.)

Chọn tất cả element có class xác định. Cú pháp: .ten-class

  • Ví dụ: .btn-primary chọn tất cả element có class "btn-primary".
  • Kết hợp nhiều class: .btn.btn-primary.btn-lg (element phải có đủ 3 class).
  • Ưu: Dễ đọc, ngắn gọn. Nhược: Class có thể thay đổi, không unique.

2. Sử dụng ID Selector (#)

Chọn element duy nhất có id xác định. Cú pháp: #ten-id

  • Ví dụ: #login-button.
  • ID nên unique trong trang (chuẩn HTML).
  • Ưu: Nhanh nhất, unique. Nhược: Dev có thể thay đổi ID, hoặc ID auto-generated (dynamic).

3. Sử dụng Attribute Selector [attribute='value']

Chọn element dựa trên thuộc tính và giá trị. Cú pháp: tagname[attribute='value']

  • Ví dụ: input[name='username'], a[href*='dashboard'], div[data-testid='submit-btn'].
  • Toán tử: = (bằng), ^= (bắt đầu), $= (kết thúc), *= (chứa), ~= (từ trong danh sách cách nhau bởi space).
  • Ưu: Rất linh hoạt, ổn định nếu dùng attribute semantic (name, data-*, aria-*).

Ví dụ Selenium Java

Ví dụ 1: Tìm bằng Class

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class CssClassExample {
    public static void main(String[] args) {
        System.setProperty("webdriver.chrome.driver", "path/to/chromedriver");
        WebDriver driver = new ChromeDriver();
        driver.get("https://www.example.com");
        
        // Tìm input search bằng class
        driver.findElement(By.cssSelector(".gsc-input")).sendKeys("Selenium");
        
        driver.quit();
    }
}

Ví dụ 2: Tìm bằng ID

public class CssIdExample {
    public static void main(String[] args) {
        WebDriver driver = new ChromeDriver();
        driver.get("https://www.example.com");
        
        // Tìm bằng ID
        driver.findElement(By.cssSelector("#gsc-i-id1")).sendKeys("Selenium");
        
        driver.quit();
    }
}

Ví dụ 3: Tìm bằng Tag + Attribute

public class CssAttributeExample {
    public static void main(String[] args) {
        WebDriver driver = new ChromeDriver();
        driver.get("https://www.example.com");
        
        // Tìm input có name='search'
        driver.findElement(By.cssSelector("input[name='search']")).sendKeys("Selenium");
        
        driver.quit();
    }
}

CSS Selector nâng cao (Advanced)

Selector Ý nghĩa Ví dụ
parent > childDirect childul > li
ancestor descendantDescendant (bất kỳ cấp).sidebar a
adjacent + siblingAnh em liền kềh2 + p
general ~ siblingAnh em chung chah2 ~ p
:nth-child(n)Con thứ ntr:nth-child(2)
:first-child / :last-childCon đầu / cuốili:first-child
:not(selector)Loại trừinput:not([type=hidden])
:contains('text')Chứa text (chỉ Selenium, không phải CSS chuẩn)button:contains('Submit')

Best Practices cho Selenium

  1. Ưu tiên data-* attributes: [data-testid="submit-btn"] - dev không đổi, tách biệt test vs style.
  2. Tránh XPath tuyệt đối (/html/body/div[2]...) - cực kỳ mong manh.
  3. Kết hợp nhiều selector: button.btn-primary[type='submit'] - chắc chắn hơn.
  4. Sử dụng DevTools: Chuột phải element → Copy → Copy selector.
  5. Test selector trong Console: $$('.selector') (Chrome) hoặc document.querySelectorAll().