Is it possible in Selenium to add an XPath parameter dynamically?

I have following code:

@FindBy(how = How.XPATH, using = "//div[@class='boxes']")
public List<WebElement> boxes;

String randomString = "something";
String startLocator = "//div[@class='cardLabel'][contains(text(), '";
String endLocator = "')]";

Is it possible to use boxes locator somehow and append text parameter?

  • You cannot use @FindBy with a variable, but you can use variables in xpaths in other scenarios. There are several methods, but I like to use replace() and start with a replaceable parameter in the xpath, something like //tr[@account='%AcctNo%'] and then replace %AcctNo% with the actual account number in a loop, for example. Mar 21, 2019 at 20:16

1 Answer 1


Short answer, no

@FindBy is an annotation in Java, and as such, it happens BEFORE the code is run. So well before you reach the webpage, @FindBy has finalized.

Long answer, no, but you can come close

You can however build xpath (and css) via String variables. They just need to be final so they can never change.

private final String xModal = "//div[@class='content']/div[@class='modal']";
private final String xModalHeader = "/div[@class='modal-header']";
private final String xModalBody = "/div[@class='modal-body']";
private final String xModalFooter = "/div[@class='modal-footer']";

@FindBy(xpath = xModal + xModalFooter + "/a[@class='btn-cancel']";
private WebElement searchModalCancel;

@FindBy(xpath = xModal + xModalFooter + "/a[@class='btn-submit']";
private WebElement searchModalSubmit;

It's very useful when dealing with a lot of similar elements.

In your case:

String final randomString = "something";
String final startLocator = "//div[@class='cardLabel'][contains(text(), '";
String final endLocator = "')]";
wait.until(ExpectedConditions.elementToBeClickable(By.xpath(startLocator + randomString + endLocator)));

would work.

In your example, you actually aren't using boxes at all. You would need some sort if iteration to loop through each box and wait for it to be clickable.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.