多测师是一家拥有先进的教学理念,强大的师资团队,业内好评甚多的接口自动化测试培训机构!

17727591462

联系电话

您现在所在位置:接口自动化测试培训 > 新闻资讯

Selenium常用的js总结-自动化测试

更新时间:2022-04-26 09:21:00 作者:多测师 浏览:305

  1、 对input执行输入

  直接设置value属性, 此方法主要应对输入框自动补全以及readonly属性的element,sendkeys不稳定

Selenium常用的js总结-自动化测试

  比如:

  //inputbox is a WebElement

  JavascriptExecutor js = (JavascriptExecutor) driver;

  js.executeScript("arguments[0].value=\"北京\"", from_inpox);

  对此可以封装一个typeQuick的方法

  /**

  * @author Young

  * @param locator

  * @param values

  * @throws Exception

  */

  protected void typeQuick(Locator locator, String values) throws Exception {

  WebElement e = findElement(driver, locator);

  log.info("type value is: " + values);

  JavascriptExecutor js = (JavascriptExecutor) driver;

  js.executeScript("arguments[0].value=\""+values+"\"", e);

  去掉只读属性

  JavascriptExecutor js = (JavascriptExecutor) driver;

  js.executeScript("arguments[0].removeAttribute(\"+"readonly"+\")", e);

  2.对富文本框的操作

  主要应对富文本框,可以封装获取富文本框内容和设置富文本路况内容的方法

  JavascriptExecutor js = (JavascriptExecutor) driver;

  WebElement editor = driver.findElement(By.tagName("body"));

  js.executeScript(

  "arguments[0].innerHTML = '

  Selenium Test

  I love Selenium

  this article Post By Selenium WebDriver

  Create By Young

  '",

  editor);

  设置富文本框内容

  /**

  * @author Young

  * @param locator

  * @param text

  */

  protected void setRichTextBox(Locator locator, String text) {

  WebElement e = findElement(driver, locator);

  log.info("type value is: " + text);

  JavascriptExecutor js = (JavascriptExecutor) driver;

  js.executeScript("arguments[0].innerHTML = \"" + text + "\"", e);

  }

  获取富文本框内容:

  /**

  * @author Young

  * @param locator

  * @param text

  * @return

  */

  protected String getRichTextBox(Locator locator, String text) {

  WebElement e = findElement(driver, locator);

  log.info("type value is: " + text);

  JavascriptExecutor js = (JavascriptExecutor) driver;

  String result=(String) js.executeScript("arguments[0].getInnerHTML()", e);

  return result;

  }

  3. 滚动到指定位置

  为啥使用滚动? 因为如果页面没有完全显示,element如果是在下拉之后才能显示出来,只能先滚动到该元素才能进行click,否则是不能click操作

  JavascriptExecutor js=(JavascriptExecutor)driver;

  // roll down and keep the element to the center of browser

  js.executeScript("arguments[0].scrollIntoViewIfNeeded(true);", download);

  可以封装滚动到元素的方法的

  /**

  * @author Young

  * @param locator

  */

  protected void scrollToElement(Locator locator) {

  WebElement e = findElement(driver, locator);

  log.info("scroll view element");

  JavascriptExecutor js = (JavascriptExecutor) driver;

  // roll down and keep the element to the center of browser

  js.executeScript("arguments[0].scrollIntoViewIfNeeded(true);", e);

  }

  以上内容为大家介绍了自动化测试中的Selenium常用的js总结,本文由多测师亲自撰写,希望对大家有所帮助。了解更多自动化测试相关知识:https://www.aichudan.com/xwzx/

联系电话

17727591462

返回顶部