我正在尝试使用 Selenium PageObjects 为标签上缺少很多方便的 id
或 class
属性的页面建模,所以我发现我需要开发更有创意的方法来识别页面上的元素。其中有一个类似下面的模式:
<div id="menuButtons">
<a><img src="logo.png" alt="New"></a>
<a><img src="logo2.png" alt="Upload"></a>
</div>
如果能够创建自定义 findBy 搜索以便能够通过其包含的图像标签的替代文本识别链接,那将很方便,因此我可以执行如下操作:
@FindByCustom(alt = "New")
public WebElement newButton;
上面的确切格式并不重要,但重要的是它继续与 PageFactory.initElements
一起工作。
最佳答案
作者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
关于java - 如何扩展 Selenium 的 FindBy 注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35185404/