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-primarychọ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 > child | Direct child | ul > li |
ancestor descendant | Descendant (bất kỳ cấp) | .sidebar a |
adjacent + sibling | Anh em liền kề | h2 + p |
general ~ sibling | Anh em chung cha | h2 ~ p |
:nth-child(n) | Con thứ n | tr:nth-child(2) |
:first-child / :last-child | Con đầu / cuối | li: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
- Ưu tiên data-* attributes:
[data-testid="submit-btn"]- dev không đổi, tách biệt test vs style. - Tránh XPath tuyệt đối (
/html/body/div[2]...) - cực kỳ mong manh. - Kết hợp nhiều selector:
button.btn-primary[type='submit']- chắc chắn hơn. - Sử dụng DevTools: Chuột phải element → Copy → Copy selector.
- Test selector trong Console:
$$('.selector')(Chrome) hoặcdocument.querySelectorAll().