我正在尝试使用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搜索以通过其包含的图像标记的alt文本标识链接,这样做将非常方便,因此我可以这样做:
@FindByCustom(alt = "New")
public WebElement newButton;上面的确切格式并不重要,但重要的是它继续与PageFactory.initElements一起工作。
发布于 2016-02-03 19:46:22
这个文章的作者扩展了'FindBy‘注释以支持他的需求,您可以使用它来覆盖’FindBy‘并实现您的on。
编辑的代码示例:
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> taghttps://stackoverflow.com/questions/35185404
复制相似问题