繁体   English   中英

如何扩展Selenium的FindBy注释

[英]How to extend Selenium's FindBy annotation

我正在尝试使用Selenium PageObjects来建模一个在标签上缺少很多方便的idclass属性的页面,所以我发现我需要开发更有创意的方法来识别页面上的元素。 其中包括如下模式:

<div id="menuButtons">
    <a><img src="logo.png" alt="New"></a>
    <a><img src="logo2.png" alt="Upload"></a>
</div>

能够创建自定义findBy搜索以便能够通过其包含的图像标记的alt文本来标识链接会很方便,所以我可以执行以下操作:

@FindByCustom(alt = "New")
public WebElement newButton;

上述的确切格式并不重要,但重要的是它继续使用PageFactory.initElements

本文作者扩展了'FindBy`注释以支持他的需求。 您可以使用它来覆盖'FindBy'并实现您的实现。

编辑过的代码示例:

private static class CustomFindByAnnotations extends Annotations {

    protected By buildByFromLongFindBy(FindBy findBy) {
        How how = findBy.how();
        String using = findBy.using();

        switch (how) {
            case CLASS_NAME:
                return By.className(using);
            case ID:
                return By.id(using);
            case ID_OR_NAME:
                return new ByIdOrName(using);
            case LINK_TEXT:
                return By.linkText(using);
            case NAME:
                return By.name(using);
            case PARTIAL_LINK_TEXT:
                return By.partialLinkText(using);
            case TAG_NAME:
                return By.tagName(using);
            case XPATH:
                return By.xpath(using);
            case ALT:
                return By.cssSelector("[alt='" + using " + ']");
            default:
                throw new IllegalArgumentException("Cannot determine how to locate element " + field);
        }
    }
}

请注意我自己没有尝试过。 希望能帮助到你。

如果你只是想要<a>标签,你可以使用xpath找到元素并使用/..一级调整/..

driver.findElement(By.xpath(".//img[alt='New']/.."));

或者您可以将按钮放在列表中并通过索引访问它们

List<WebElement> buttons = driver.findElements(By.id("menuButtons")); //note the spelling of findElements
// butttons.get(0) is the first <a> tag

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM