如何在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();
}
}
输出

广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP