Selenium Webdriver 使用类名进行定位策略
通过类名可以用作 Selenium webdriver 中的定位策略。我们可利用带有定位符的类属性(如类名、css 和 xpath)识别元素。要使用 css 定位 web 元素,语法为 tagname[class='value'],要使用的方法为 By.cssSelector。
要使用 xpath 定位 web 元素,语法为 //tagname[@class='value']。然后,我们必须使用 By.xpath 方法来定位它。要使用定位符类名定位元素,我们必须使用 By.className 方法。
我们来看一下具有类属性的 web 元素的 html 代码 −

语法
WebElement elm = driver. findElement(By.className("input__input"));
WebElement p = driver.findElement(By.xpath("//input[@class = ' input__input']"));
WebElement t = driver. findElement(By.cssSelector("input[class=' input__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 ClsNameStrategy{
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 class name
WebElement elm = driver.findElement(By.className("input__input"));
elm.sendKeys("abc@gmail.com");
//identify with cssSelector
WebElement c= driver.findElement(By.cssSelector("input[class='input__input']"));
String str = c.getAttribute("value");
System.out.println("Value entered is : " + str);
//identify with xpath
WebElement x = driver.
findElement(By.xpath("//input[@class='input__input']"));
x.clear();
driver.close();
}
}输出

广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP