首頁  >  文章  >  web前端  >  如何在 Selenium 中使用 CSS 選擇器作為定位器?

如何在 Selenium 中使用 CSS 選擇器作為定位器?

WBOY
WBOY轉載
2023-08-28 23:57:051384瀏覽

我們可以在Selenium webdriver中使用CSS選擇器定位元素。建立CSS表達式的一般形式是tagname[attribute='value']。我們可以利用id和class屬性來創建CSS。

使用id時,CSS表達式的語法是tagname#id。例如,對於CSS表達式 - input#txt-loc,input是tagname,txt-loc是id屬性的值。

使用類別名稱時,CSS表達式的語法是tagname.class。例如,對於CSS表達式 - input.txt-cls,input是tagname,txt-cls是class屬性的值。

如果一個網頁元素element(parent)有n個子元素(children),我們想要定位第n個子元素,CSS表達式的語法是nth-of-type(n)。

如何在 Selenium 中使用 CSS 选择器作为定位器?

在上面的html中,如果我們想要定位父級ul的第四個li,即文字為「Questions and Answers」的錨點元素,CSS應該是ul.reading li:nth-of-type(4)。同樣,要辨識最後一個子元素,CSS應該是ul.reading li:last-child。

對於具有動態值的屬性,我們可以使用符號^=來識別屬性值以特定文字開頭的元素。例如,input[name^='qa1'] [這裡input是tagname,name屬性的值以qa1開頭]。

對於具有動態值的屬性,我們可以使用符號$=來識別屬性值以特定文字結尾的元素。例如,input[class$='loc'] [這裡input是tagname,class屬性的值以loc結尾]。

對於具有動態值的屬性,我們可以使用符號*=來識別屬性值包含特定子字串的元素。例如,input[name*='sub'] [這裡input是tagname,name屬性的值包含子字串sub]。

範例

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();
   }
}
#

以上是如何在 Selenium 中使用 CSS 選擇器作為定位器?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除