我正在测试页面上的元素(例如 //img
或 //i
是否具有 alt
属性。
我找不到检测属性何时根本不存在的方法。
这是 WebElement。只是一个没有 alt 属性的 img。
<img class="gsc-branding-img" src="https://www.google.com/cse/static/images/1x/googlelogo_grey_46x15dp.png" srcset="https://www.google.com/cse/static/images/2x/googlelogo_grey_46x15dp.png 2x"/>
这是我的代码,试图确定 alt 的存在。我知道这不是全部,我只是尝试了一切。
WebElement we == driver.findElement(By.xpath("(//img)[1]"));
String altAttribute = we.getAttribute("alt");
if(altAttribute == null || altAttribute =="" || altAttribute == " ")
{
//attribute not found
}
好像返回的是空字符串……比如下面的代码返回“beforeAfter”
System.out.println("before"+altAttribute+"After");
但是,我的 if
语句没有捕捉到返回值,所以我不知道该怎么做。
最佳答案
如果该属性不存在,则返回null,如果存在但未设置,则返回空字符串。如果是这样,我认为您的示例就是这种情况。那么你应该使用 equal
方法来比较字符串而不是 ==
运算符。
下面的例子是关于谷歌搜索框的,搜索框没有xxx属性,所以它会返回null
driver = new ChromeDriver();
driver.get("http://google.com");
WebElement ele = driver.findElement(By.name("q"));
String attr = ele.getAttribute("xxx");
if (attr == null){
System.out.print("Attribute does not exist");
}
else if (attr.equals("")){
System.out.print("Attribute is empty string");
}
您可以自己尝试编写以下 html 并将其保存为测试。 HTML:
<html>
<head>
</head>
<body>
<p id="one">one</p>
<p id="two" data-se="">two</p>
<p id="three" data-se="something">three</p>
</body>
</html>
然后编写如下所示的 Web 驱动程序脚本:
driver.get("file:///<PATH_TO_HTML_ABOVE>/test.html");
WebElement one = driver.findElement(By.id("one"));
WebElement two = driver.findElement(By.id("two"));
WebElement three = driver.findElement(By.id("three"));
System.out.println("Does one have the data-se attribute?: '" + one.getAttribute("data-se") + "'");
System.out.println("Does two have the data-se attribute?: '" + two.getAttribute("data-se") + "'");
System.out.println("Does three have the data-se attribute?: '" + three.getAttribute("data-se") + "'");
这将为您提供以下输出:
Does one have the data-se attribute?: 'null'
Does two have the data-se attribute?: ''
Does three have the data-se attribute?: 'something'
关于java - 如何使用 Selenium Webdriver 测试 WebElement 属性是否存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44847608/