WEB端UI自动化测试(四)元素的定位

一、元素定位

selenium提供了接口的抽象方法findElement(),通过传入抽象参数by来定位元素,查看源码,发现支持的方式有很多

public static By id(String id)
    {
        if(id == null)
            throw new IllegalArgumentException("Cannot find elements with a null id attribute.");
        else
            return new ById(id);
    }

    public static By linkText(String linkText)
    {
        if(linkText == null)
            throw new IllegalArgumentException("Cannot find elements when link text is null.");
        else
            return new ByLinkText(linkText);
    }

    public static By partialLinkText(String linkText)
    {
        if(linkText == null)
            throw new IllegalArgumentException("Cannot find elements when link text is null.");
        else
            return new ByPartialLinkText(linkText);
    }

    public static By name(String name)
    {
        if(name == null)
            throw new IllegalArgumentException("Cannot find elements when name text is null.");
        else
            return new ByName(name);
    }

    public static By tagName(String name)
    {
        if(name == null)
            throw new IllegalArgumentException("Cannot find elements when name tag name is null.");
        else
            return new ByTagName(name);
    }

    public static By xpath(String xpathExpression)
    {
        if(xpathExpression == null)
            throw new IllegalArgumentException("Cannot find elements when the XPath expression is null.");
        else
            return new ByXPath(xpathExpression);
    }

    public static By className(String className)
    {
        if(className == null)
            throw new IllegalArgumentException("Cannot find elements when the class name expression is null.");
        else
            return new ByClassName(className);
    }

    public static By cssSelector(String selector)
    {
        if(selector == null)
            throw new IllegalArgumentException("Cannot find elements when the selector is null");
        else
            return new ByCssSelector(selector);
    }

我常用的定位方式有三种ById,ByXpath,ByName

二、元素的操作

我们找到元素之后,下面就要对元素进行操作了,在eclipse中,我们能看到findElement支持的方法有很多

最常用的就是点击了,就是click()。其他常用的比如clear()可以清空输入框,sendKeys()向文本框中塞值,getText()获取元素文本 。

三、元素定位问题

有时候我们明明能看到元素,就是定位不到,可能的原因有下面几种:

1.定位方式不对,换成id,xpath,或者linktext试试

2.元素没有加载完全,我们可以用显示等待或隐式等待的方式判断元素是否加载成功,相关内容放在后面的章节再说

3.页面Frame切换了,在测试过程中,经常会需要点击跳转到新的选项卡,此时需要切换Frame才能定位到元素,这部分后面也会讲的

4.元素是动态变化的,无法定位到

元素定位不到的原因很多,需要我们平时使用的时候仔细总结,找到相应的解决方法。

猜你喜欢

转载自www.cnblogs.com/guizang/p/11694370.html