有时候web测试会遇到一些比较难处理的场景:
比如检查文字的样式(太长就显示...等),还有就是浏览器源生的控件(比如滚动条,弹出的windows对话框等等),
这时候,selenium的API往往没法直接处理,我们需要结合实际情景借助其他的方法,比如借助javascript等。
场景一:检查文本的样式
以百度首页为例(先登陆一下百度账号,最好用邮箱,就会发现邮箱是缩略显示的,如:XX...X@XXX.com),怎样去检查一段文本是否使用了省略号...呢?
因为,我们直接使用getText()这个API的话,你会发现得到的文本是不含有省略号...的。
这时,我们要从style入手,借助getCssValue()这个API去完成:
参考代码如下:
package selTest.web.testBD; import org.openqa.selenium.By; import org.testng.Assert; import org.testng.annotations.Test; import common.InitialDriver; public class test1 extends InitialDriver{ @Test public void test() { initDriver(); driver.get("http://www.baidu.com"); driver.manage().window().maximize(); webelement = driver.findElement(By.xpath("//a[@id = 's_username_top']/span")); String textStyle = webelement.getCssValue("text-overflow"); System.out.println("textStyle :" + textStyle); Assert.assertTrue(textStyle.equals("ellipsis"), "Fail, the text does't use style of ellipsis "); } }
说明:从上面的截图可以看到,显示出来的登录用户这个元素,style里面,text-overflow的值是ellipsis(即采用的是省略号的形式)。
因此,我们可以用上述代码去检查一段文字里面是否使用了某种格式。
场景二:检查是否有滚动条生成
就以我们写博客的页面为例,当我们博客的内容超过一定行数的时候,页面就会生成滚动条(如下图):
我们如何检查这个滚动条是否生成了呢?因为selenium是没有API去处理浏览器源生的控件,比如滚动条的。
这里我们借助javascript和getCssValue()这个API来处理:
方法说明:判断滚动条是否存在,主要是依据是scrollHeight > clientHeight; (水平)scrollWidth> clientWidth(垂直). 但是仅这一个条件可能会得到很多元素(不一定是滚动条)。因此还要加上getCssValue("overflow-x")和getCssValue("overflow-y")来判断。
附上参考代码:(以下代码检查的是,符合某个条件的时候,自动出现的滚动条,不是检查浏览器源生的一直存在的滚动条)
public static boolean isHorizontalScrollbarPresent() throws Exception { List<WebElement> wes = new ArrayList<>(); Boolean isScrollBarPresent = false; int count = 0; wes = WebDriverCommon.getWebElements(By.xpath("*//div")); for (WebElement we : wes) { if (Integer.parseInt(we.getAttribute("clientWidth")) < Integer.parseInt(we.getAttribute("scrollWidth"))) { if (we.getCssValue("overflow-x").equals("auto")) { count++; } } } if (count > 0) { isScrollBarPresent = true; Action.info("Horizontal scrollbar is present."); } else { Action.info("Horizontal scrollbar is not present."); } return isScrollBarPresent; } public static boolean isVerticalScrollbarPresent() throws Exception { List<WebElement> wes = new ArrayList<>(); Boolean isScrollBarPresent = false; int count = 0; wes = WebDriverCommon.getWebElements(By.xpath("*//div")); for (WebElement we : wes) { if (Integer.parseInt(we.getAttribute("clientHeight")) < Integer.parseInt(we.getAttribute("scrollHeight"))) { if (we.getCssValue("overflow-y").equals("auto")) { count++; } } } if (count > 0) { isScrollBarPresent = true; Action.info("Vertical scrollbar is present."); } else { Action.info("Vertical scrollbar is not present."); } return isScrollBarPresent; } 场景三:处理frame
我们写博客的页面是有frame的:我们要写的内容就在id=xhe0_iframe这个frame里面(如下图)
当我们要处理的元素在frame里面时,我们要先跳到frame里:driver.switchTo().frame("xhe0_iframe");这里选取的参数是这个frame的id属性。
否则,selenium会报找不到元素的错误。
总之,实际的web测试,我们会遇到很多selenium的API无法直接解决的问题,这时我们可以借助其他API来间接处理,有时还要利用到javascript等。