如何从 Selenium 获取元素属性?
我们可以在 Selenium webdriver 中获取元素属性。getAttribute() 方法用于获取 html 文档中的属性值。在 html 代码中,属性及其值以键值对的形式出现。
一些常见的 html 属性包括 disabled、alt、id、href、style、title 和 src。我们要获取的属性的值作为参数传递给该方法。
我们考虑一个 html 代码,从中我们将获取 src 属性。src 属性的值应为/about/images/logo.png。

示例
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
public class GetSrcAttribute{
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver","C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
WebDriver driver = new ChromeDriver();
String u = "https://tutorialspoint.com/about/about_careers.htm"driver.get(u);
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
// identify element
WebElement t=driver.findElement(By.xpath("//img[@class='tp-logo']"));
// get src attribute with getAttribute()
System.out.println("Src attribute is : " + t.getAttribute("src"));
driver.close();
}
}
Output

Advertisement
数据结构
计算机网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP