如何在 Selenium 中使用“CSS 選擇器”查詢元素?


我們可以使用 Selenium webdriver 透過 css 定位器查詢元素。要使用 css 識別元素,表示式應為 tagname[attribute='value']。

我們還可以專門使用 id 屬性來建立 css 表示式。

使用 id 時,css 表示式的格式應為 tagname#<id>。例如,input#txt [此處 input 是標籤名,txt 是 id 屬性的值]。

使用 class 時,css 表示式的格式應為 tagname.<class>。例如,input.cls-txt [此處 input 是標籤名,cls-txt 是 class 屬性的值]。

如果父元素有 n 個子元素,並且我們想識別第 n 個子元素,則 css 表示式應包含 nth-of –type(n)。

在上面的程式碼中,如果我們想識別 ul[問答] 的第四個 li 子元素,則 css 表示式應為 ul.reading li:nth-of-type(4)。同樣,要識別最後一個子元素,css 表示式應為 ul.reading li:last-child。

對於值動態變化的屬性,我們可以使用 ^= 來定位其值以特定文字開頭的元素。例如,input[name^='qa'] [此處 input 是標籤名,name 屬性的值以 qa 開頭]。

對於值動態變化的屬性,我們可以使用 $= 來定位其值以特定文字結尾的元素。例如,input[class$='txt'] [此處 input 是標籤名,class 屬性的值以 txt 結尾]。

對於值動態變化的屬性,我們可以使用 *= 來定位其值包含特定子文字的元素。例如,input[name*='nam'] [此處 input 是標籤名,name 屬性的值包含子文字 nam]。

示例

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 LocatorCss{
   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://www.linkedin.com/");
      //identify element with css
      WebElement n = driver.
      findElement(By.cssSelector("input[id='session_key']"));
      n.sendKeys("Java");
      String str = n.getAttribute("value");
      System.out.println("Attribute value: " + str);
      driver.quit();
   }
}

輸出

更新於: 2021年4月6日

5K+ 瀏覽量

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告