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")) ;
}
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;
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!
What you are trying to do is not easily achievable without writing custom
ElementLocatorFactory
.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]")
.But if you really want to do it with shorter
@FindBy
annotations, you can go forElementLocatorFactory
.Class with an element that will provide you with the context:
Its child:
Usage:
You do not need to write a custom
ElemLocatorFactory
, just useorg.openqa.selenium.support.pagefactory.DefaultElementLocatorFactory
instead:The approach mentioned above works, but if you're using xpath, make sure that your 'child' element has a
.//
in front to make it relative.