0

Suppose I have an XPath to identify an element like this:

//div[@id='%s1']//div[@class='%s2']

The values for both s1 and s2 are to be passed at runtime. Is it possible to form an XPath (String) by passing these two variables from my code?

Ratmir Asanov
  • 6,237
  • 5
  • 26
  • 40
source
  • 21
  • 5
  • 1
    You can build the XPath expression in Java code before calling Selenium, right? e.g. `String xpathToUse = "//div[@id='" + s1 + "']//div[@class='" + s2 + "']"` – Grzegorz Oledzki Nov 13 '17 at 09:11
  • Please clarify your specific problem or add additional details to highlight exactly what you need. As it's currently written, it’s hard to tell exactly what you're asking. See the [How to Ask](https://stackoverflow.com/help/how-to-ask) page for help clarifying this question. – undetected Selenium Nov 13 '17 at 10:54
  • Possible duplicate of [How to pass variable parameter into XPath expression?](https://stackoverflow.com/questions/30352671/how-to-pass-variable-parameter-into-xpath-expression) – kjhughes Nov 13 '17 at 12:33

1 Answers1

0
public String varLocator(String locator, String holder1, String param1, String holder2, String param2) {

return locator.replace(holder1, param1).replace(holder2, param2);

}

public void sample() {

String eleLocator = "//div[@id='%s1']//div[@class='%s2']";

WebElement foo = driver.findElement(By.xpath(varLocator(eleLocator, "%s1", "foo", "%s2", "bar")));

}
Bill Hileman
  • 2,798
  • 2
  • 17
  • 24