简体   繁体   中英

How to extend Selenium's FindBy annotation

I'm trying to use Selenium PageObjects to model a page that lacks a lot of convenient id or class attributes on the tags, so I'm finding that I need to develop more creative ways to identify elements on a page. Among them is a pattern like the following:

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

It would be convenient to be able to create a custom findBy search to be able to identify a link by the alt text of its contained image tag, so I could do something like the following:

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

The exact format of the above isn't important, but what's important is that it continue to work with PageFactory.initElements .

The author of this article extended the 'FindBy` annotation to support his needs. You can use this to override the 'FindBy' and make your on implementation.

Edited code sample:

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);
        }
    }
}

Please note I didn't try it myself. Hope it helps.

If you simply want the <a> tag you can use xpath to find the element and go one level up using /..

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

Or you can put the buttons in list and access them by index

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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