2016-02-03 29 views
1

我想要使用Selenium PageObjects来建模一个页面,该页面在标签上缺少很多方便的idclass属性,所以我发现我需要开发更有创意的方法来识别元素在一个页面上。其中之一是像下面这样的模式:如何扩展Selenium的FindBy注解

<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工作。

回答

3

article的作者扩展了'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