[英]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. 我正在尝试使用Selenium PageObjects来建模一个在标签上缺少很多方便的
id
或class
属性的页面,所以我发现我需要开发更有创意的方法来识别页面上的元素。 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: 能够创建自定义findBy搜索以便能够通过其包含的图像标记的alt文本来标识链接会很方便,所以我可以执行以下操作:
@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
. 上述的确切格式并不重要,但重要的是它继续使用
PageFactory.initElements
。
The author of this article extended the 'FindBy` annotation to support his needs. 本文作者扩展了'FindBy`注释以支持他的需求。 You can use this to override the 'FindBy' and make your on implementation.
您可以使用它来覆盖'FindBy'并实现您的实现。
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 /..
如果你只是想要
<a>
标签,你可以使用xpath找到元素并使用/..
一级调整/..
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.