问题描述
我正在尝试将我的selenium测试转换为使用Page Object Model(以及扩展名为@FindBy)。我有几个这样的对象定义:
I'm trying to convert my selenium tests to use the Page Object Model (and, by extension, @FindBy). I have several object definitions like this:
public WebElement objectParent() {
return driver.findElement(By.name("parent-id")) ;
}
public WebElement objectChild() {
WebElement elem = objectParent();
return elem.findElement(By.name("child-id")) ;
}
将父对象转换为使用 @FindBy
很简单:
Converting the parent object to using @FindBy
is easy:
@FindBy(name = "parent-id")
WebElement parentObj;
基本上,如果可能,我想做这样的事情(我知道这不是真正的代码,这只是一个伪示例:
Basically, I want to do something like this, if possible (I know this isn't real code, this is just a pseudo example:
@FindBy(name = "parent-id")
WebElement parentObj;
@FindBy(parentObj.name = "child-id")
WebElement childObj;
但有没有办法使用 @FindBy?
来定位元素中的子元素。我需要做的它是这样的,因为我的目标是页面上的特定元素可能与页面上的其他元素共享相同的名称或类名。谢谢!
But is there a way too target the child element within the parent element using @FindBy?
. I need to do it this way because I am targeting specific elements on the page that may share the same name or class name with other elements on the page. Thanks!
推荐答案
如果不编写自定义 ElementLocatorFactory
,你要做的事情是不容易实现的。
What you are trying to do is not easily achievable without writing custom ElementLocatorFactory
.
首先我我真的建议使用。
这样可以轻松获取:
3rd < t能够>
就像这样: @FindBy(xpath =\\table [3])
和...
第二个< li>
在第三个表中就像这样: @FindBy(xpath =\\table [3] \\ \\li [2])
。
Firstly I would really recommend using XPath.This would make it easy lot to grab the:
3rd <table>
just like this: @FindBy(xpath = "\\table[3]")
and...
2nd <li>
in the 3rd table just like this: @FindBy(xpath = "\\table[3]\li[2]")
.
但是如果你真的想用更短的 @FindBy
注释来做,你可以去 ElementLocatorFactory
。
But if you really want to do it with shorter @FindBy
annotations, you can go for ElementLocatorFactory
.
public class FindByContextModifier implements ElementLocatorFactory {
private final SearchContext context;
public FindByContextModifier(final SearchContext context) {
this.context = context;
}
public ElementLocator createLocator(final Field field) {
return new DefaultElementLocator(context, field);
}
}
带有元素的类,它将为您提供上下文:
Class with an element that will provide you with the context:
public class Parent {
@FindBy(name = "myTable")
WebElement table;
public WebElement getTable() {
return this.table;
}
}
其子女:
public class Child {
@FindBy(name = "particular")
WebElement specialTableListElement;
}
用法:
Parent parent = PageFactory.initElements(driver, Parent.class);
FindByContextModifier parentContext = new FindByContextModifier(parent.getTable());
Child child = new Child();
// This will look for the name "particular" inside the element with "myTable" name
PageFactory.initElements(parentContext, child);
这篇关于Selenium / PageFactory:使用父元素的@FindBy查找子元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!