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

Cách sử dụng CSS Selector làm locator trong Selenium

Giới thiệu

Chúng ta có thể định vị các phần tử với locator CSS Selector trong Selenium WebDriver. Biểu thức chung để tạo một CSS selector là tagname[attribute='value']. Chúng ta có thể sử dụng thuộc tính id và class để tạo CSS selector.

Với id

Cú pháp: tagname#id. Ví dụ: input#txt-loc, trong đó input là tagname, txt-loc là giá trị id.

Với class

Cú pháp: tagname.class. Ví dụ: input.txt-cls, trong đó input là tagname, txt-cls là giá trị class.

Chọn phần tử con thứ n

Nếu có n phần tử con của một phần tử cha, và muốn chọn con thứ n, cú pháp: nth-of-type(n).

Cách sử dụng CSS Selector làm locator trong Selenium

Trong HTML trên, nếu muốn chọn thẻ li thứ 4 của ul cha (anchor có text "Questions and Answers"), CSS selector sẽ là: ul.reading li:nth-of-type(4). Tương tự, để chọn con cuối cùng: ul.reading li:last-child.

Thuộc tính giá trị động

  • Bắt đầu bằng (^=): input[name^='qa1'] - chọn input có name bắt đầu bằng "qa1".
  • Kết thúc bằng ($=): input[class$='loc'] - chọn input có class kết thúc bằng "loc".
  • Chứa chuỗi con (*=): input[name*='sub'] - chọn input có name chứa "sub".

Ví dụ Selenium (Java)

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 CSSLocator{ 
  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(10, TimeUnit.SECONDS); 
    // URL launch 
    driver.get("https://www.linkedin.com/"); 
    // identify element 
    WebElement m = driver.findElement(By.cssSelector("input[id='session_key']")); 
    // enter text 
    m.sendKeys("Java"); 
    String s = m.getAttribute("value"); 
    System.out.println("Attribute value: " + s); 
    // close browser 
    driver.close(); 
  } 
}