1.当元素不存在的话,通常会抛出NoSuchElementException 导致测试失败,但有时候,我们需要去确保页面元素不存在,才是我们正确的验收条件下面的方法可以用来判定页面元素是否存在
Python版本
def isPresent(self):
try:
driver.find_element_by_xpath(Xpath)
except NoSuchElementException, e:
return False
return True
Java版本
public boolean doesWebElementExist(WebDriver driver, By selector)
{
try
{
driver.findElement(selector);
return true;
}
catch (NoSuchElementException e)
{
return false;
}
}
使用片段
WebDriver driver = new InternetExplorerDriver();
By locator = By.id("id");
doesWebElementExist(driver,locator);
2.类似于seleniumRC中的isTextPresent 方法
用xpath匹配所有元素(//*[contains(.,'keyword')]),判断是否存在包含期望关键字的元素。
使用时可以根据需要调整参数和返回值。
public boolean isContentAppeared(WebDriver driver,String content) {
boolean status = false;
try {
driver.findElement(By.xpath("//*[contains(.,'" + content + "')]"));
System.out.println(content + " is appeard!");
status = true;
} catch (NoSuchElementException e) {
status = false;
System.out.println("'" + content + "' doesn't exist!"));
}
return status;
}
PS: Selenium1提供的isElementPresent方法也可解决此问题。 selenium.isElementPresent(By.Xpath("//div[@id='kw']"))
本文介绍了如何使用Selenium Webdriver来验证网页上的元素是否存在,包括Python和Java两种语言的实现方式,并提供了一个用于判断页面上是否出现特定文本的方法。
4118

被折叠的 条评论
为什么被折叠?



