如何在Selenium中使用“类名”属性查找元素?


我们可以使用类名属性Selenium webdriver以及定位器——类名、css或xpath来查找元素。要使用css识别元素,表达式应为tagname[class='value'],使用方法为By.cssSelector

要使用xpath识别元素,表达式应为//tagname[@class='value']。然后,我们必须使用方法By.xpath来定位它。要使用定位器类名定位元素,我们必须使用方法By.className

让我们来看一下具有class属性的元素的html代码:

语法

WebElement e = driver. findElement(By.className("input"));
WebElement m = driver. findElement(By.xpath("//input[@class = 'input']"));
WebElement n = driver. findElement(By.cssSelector("input[class='input']"));

示例

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 LocatorClsName{
   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://tutorialspoint.com/videotutorials/subscription.php");
      // identify element with class
      WebElement n = driver.findElement(By.className("input"));
      n.sendKeys("JavaScript");
      //identify element with cssSelector
      WebElement n = driver.
      findElement(By.cssSelector("input[class='input']"));
      String str = n.getAttribute("value");
      System.out.println("Attribute value is : " + str);
      //identify element with xpath
      WebElement p = driver.
      findElement(By.xpath("//input[@class='input']"));
      p.clear();
      driver.close();
   }
}

输出

更新于:2023年11月8日

24K+ 次浏览

启动您的职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.