在Selenium中如何通过多个类名查找div元素?
我们可以通过多个类名查找元素。如果一个元素的class属性设置了多个值,这些值用空格隔开,则称为复合类名。
让我们看看具有复合类名的网页元素的HTML代码:

如果我们同时使用toc和chapters这两个值作为类名定位符,将会出现异常。相反,规则是类名定位符只能有一个class属性值。
语法
WebElement l = driver.findElement(By.className("toc"));
//Invalid locator value with className locator
WebElement l = driver.findElement(By.className("toc chapters"));示例
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class ClssLocator{
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver",
"C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
WebDriver driver = new ChromeDriver();
//launch URL
driver.get("https://tutorialspoint.com/about/about_careers.htm/");
//identify element with className having compound classes
WebElement l = driver.findElement(By.className("toc"));
//verify if element is displayed
boolean b = l.isDisplayed();
System.out.println(b);
driver.quit();
}
}输出

使用css定位符,我们可以使用为class属性设置的所有值。方法是将所有值用点(.)连接起来,并在css表达式的开头也添加一个点(.)。
语法
WebElement l = driver.findElement(By.cssSelector(".toc.chapters"));示例
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class CssSelectorLocator{
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver",
"C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
WebDriver driver = new ChromeDriver();
//launch URL
driver.get("https://tutorialspoint.com/about/about_careers.htm/");
//identify element with css having compound classes
WebElement l = driver.findElement(By.cssSelector(".toc.chapters"));
//verify if element is displayed
boolean b = l.isDisplayed();
System.out.println(b);
driver.quit();
}
}输出

使用css和xpath定位符,我们可以通过使用class作为属性,然后将整个class值用引号括起来,来包含class属性的所有值。
语法
WebElement l = driver.findElement(By.xpath("//ul[@class='toc chapters']"));
WebElement m = driver
.findElement(By.cssSelector("ul[class='toc chapters']"));示例
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class XpathLocator{
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver",
"C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
WebDriver driver = new ChromeDriver();
//launch URL
driver.get
("https://tutorialspoint.com/about/about_careers.htm/");
//identify element with xpath having compound classes
WebElement l = driver.findElement(By.cssSelector("ul[class='toc chapters']"));
//verify if element is displayed
boolean b = l.isDisplayed();
System.out.println(b);
driver.quit();
}
}输出

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