Selenium回放脚本时timeout问题有效解决方案

发表于:2016-5-12 11:06

字体: | 上一篇 | 下一篇 | 我要投稿

 作者:吸血鬼日记    来源:51Testing软件测试网采编

  webdriver的适用代码
  1. 在5秒时间内找目标元素,找到就针对目标元素执行click
  (new WebDriverWait(driver, 5)).until(new ExpectedCondition() {
  public WebElement apply(WebDriver d) {
  return d.findElement(By.cssSelector("#quick-links > ul > li.nav-tabs-item.mc-ql-tab-item-bm > a"));
  }
  }).click();
  2. 等候页面上出现目标文本,对应IDE的waitForText, waitForElementPresent
//跟据定位类型和定位字符串定位页面元素
protected WebElement findElement(String locatorType, String locatorString) {
if (locatorType.equals(this.CssLocator)) {
return driver.findElement(By.cssSelector(locatorString));
} else if (locatorType.equals(this.IdLocator)) {
return driver.findElement(By.id(locatorString));
} else if (locatorType.equals(this.XpathLocator)) {
return driver.findElement(By.xpath(locatorString));
} else if (locatorType.equals(this.NameLocator)) {
return driver.findElement(By.name(locatorString));
} else if (locatorType.equals(this.ClassNameLocator)) {
return driver.findElement(By.className(locatorString));
} else if (locatorType.equals(this.TagNameLocator)) {
return driver.findElement(By.tagName(locatorString));
} else if (locatorType.equals(this.LinkTextLocator)) {
return driver.findElement(By.linkText(locatorString));
} else {
return driver.findElement(By.partialLinkText(locatorString));
}
}
/**
* Wait 60 seconds till text is present otherwise give timeout error, increase the waiting time if necessary
* @param text
* @param locatorType
* @param locatorString
*/
protected void waitForText(String text, String locatorType, String locatorString){
for (int second = 0;; second++) {
if (second >= 60) fail("timeout");
try {
if (text.equals(findElement(locatorType, locatorString).getText())) break;
} catch (Exception e) {
logger.error("waitForText exception:"+e);
}
try{
Thread.sleep(1000);
} catch (InterruptedException e) {
logger.error("waitForText Thread.sleep exception:"+e);
e.printStackTrace();
}
}
}
  执行完某步耗时操作之后,调用waitForText()直到出现目标文本(或者超时)再执行下步动作。
22/2<12
《2023软件测试行业现状调查报告》独家发布~

关注51Testing

联系我们

快捷面板 站点地图 联系我们 广告服务 关于我们 站长统计 发展历程

法律顾问:上海兰迪律师事务所 项棋律师
版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2024
投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

沪ICP备05003035号

沪公网安备 31010102002173号