1

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 = "')]";
wait.until(ExpectedConditions.elementToBeClickable(By.xpath(startLocator+randomString+endLocator)));

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

asked Mar 21, 2019 at 19:55
1
  • 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. Commented Mar 21, 2019 at 20:16

1 Answer 1

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.

answered Mar 21, 2019 at 22:57

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.