如何使用 Selenium WebDriver 验证元素中是否存在属性?


我们可以使用 Selenium webdriver 验证元素中是否存在属性。这是借助getAttribute 方法实现的。在 html 文档中,每个元素使用其标签与具有其值的元素属性一起标识。为了获取属性值,我们必须将元素属性作为参数传递给 getAttribute 方法。

让我们看看元素的 html 代码并获得其 src 属性的值。其 src 属性的值应该是 /about/images/logo.png

示例

代码实现。

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

输出

更新日期:2020-10-26

4K+ 查看

开启你的职业

完成课程获得认证

开始
广告
© . All rights reserved.