如何在 Selenium 中使用"类名"属性查找元素?
seleniumautomation testingtesting tools
我们可以使用 Selenium WebDriver 中的定位器(类名、CSS 或 XPath)通过类名属性查找元素。使用 CSS 定位元素时,表达式应为 tagname[class='value'],使用的方法为 By.cssSelector。
使用 XPath 定位元素时,表达式应为 //tagname[@class='value']。然后,我们必须使用 By.xpath 方法来定位它。使用定位器类名定位元素时,我们必须使用 By.className 方法。
让我们看一下带有类属性的元素的 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();
//隐式等待
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
//URL 启动
driver.get("https://www.tutorialspoint.com/videotutorials/subscription.php");
// 使用类标识元素
WebElement n = driver.findElement(By.className("input"));
n.sendKeys("JavaScript");
//使用 cssSelector 标识元素
WebElement n = driver.
findElement(By.cssSelector("input[class='input']"));
String str = n.getAttribute("value");
System.out.println("属性值为:" + str);
//使用 xpath 识别元素
WebElement p = driver.
findElement(By.xpath("//input[@class='input']"));
p.clear();
driver.close();
}
}
输出


