我正在使用Selenium在网页中搜索元素。我正在使用findElement()
的包装类和包装器方法,并使用XML将密钥传递给包装器。因此,这一切都很好。最近,我必须在不同的设置中找到许多具有类似className的元素和不同的XPATH。我尝试使用className创建自定义XPath,并尝试使用不同的特定属性来识别元素。页面结构看起来像:
<span class="app-icon">
<img class="app-icon-large" alt="WorkForce1" src="https://someWebAddress"/>
</span>
我使用的XPath是:
workXPATH = .//span[1]/img[@alt="Workforce1"]
问题是,如果我用一些随机单词替换Workforce1
,例如zenith
isDisplayed()
方法仍然返回true。并且不可能在DOM结构中存在Zenith。这让我挠头。有人知道为什么这样做的方式如何?代码是:
element.get("workXPATH").isDisplayed()
尝试以这种方式。
说明:首先使用alt
属性获取workForce1
图像的字符串。
现在使用xpath
定位器找到Webelement。
然后使用IF条件比较String
和WebElement
。
String workForce1_text = driver.findElement(By.xpath("//span/img[@alt='WorkForce1']")).getAttribute("alt");
System.out.println(workForce1_text);
WebElement element = driver.findElement(By.xpath("//span/img[@alt='WorkForce1']"));
if(element.getAttribute("alt").contentEquals(workForce1_text))
{
/*your action goes here.*/
}
isdisplayed()返回true
这是因为(XPath)在您的HTML源代码中找到的(XPath)。
所以有效例如
WebElement Image = driver.findElement(By.xpath("//*[@id='registrationForm']/div[13]/span/img")); // here you need to find unique value for your xpath if that repeated in the source
so:图像get毫无意义
另外,如果您需要从HTML属性返回值
Image.getAttribute("alt").equals("your expected results");