6

Is it possible to add a defined Java String variable to an xpath-expression? Here is some code to make it clear:

String newUser = "NewUser123";
driver.findElement(By.xpath("//td[normalize-space(text())=**newUser**]/a")).click();

The xpath should work with the variable newUser, but I don´t know how.

Stefan
  • 137
  • 1
  • 2
  • 10
  • 2
    Possible duplicate of [Java - Including variables within strings?](http://stackoverflow.com/questions/9643610/java-including-variables-within-strings) – JeffC Oct 18 '15 at 13:33
  • 2
    Why the down votes? Its a valid question! – Miek Apr 28 '17 at 18:59

6 Answers6

11

Yes, when you choose Java as your programming language while working with selenium, you can perform all things that are logically possible in Java.

Take your example, xpath is a function which takes string arguments. So Like in Java we concatenate multiple strings using +. you can do the same thing here.

String newUser = "NewUser123";
driver.findElement(By.xpath("//td[normalize-space(text())='"+newUser+"']/a")).click();
Nidhi
  • 121
  • 2
  • 5
2

In similar situations I will extract the lookup to a constant in the class, and use the String.format utility to insert the variable(s) where I need it. Note the use of %s in the example constant USER_XPATH below.

I think this is better for readability and maintenance than the inline concatenation option, but both will achieve the goal.

/** Format string for the ### xpath lookup.*/
private static final String USER_XPATH ="//td[normalize-space(text())=%s]/a";

Then you can use String.format to insert the variable you want:

 private void myMethod() {
      String newUser = "NewUser123";
      String fullXpath = String.format(USER_XPATH, newUser);
      driver.findElement(By.xpath(fullXpath)).click();
    }
Jeremiah
  • 1,145
  • 6
  • 8
  • This is nice except that `%s` needs to be included between quotes (either single or double). Otherwise, it does not work. I mean it should be `private static final USER_XPATH ="//td[normalize-space(text())='%s']/a";` – Rao May 24 '16 at 06:48
2

Xpath with variable and space

String CasesCount = Utility.WebDriverHelper.Wdriver.findElement
(By.xpath("//button[text()=' "+tabname+"']/span")).getText();

Remove this kind of special braces () in text

CasesCount  = CasesCount.replaceAll("\\(", "").replaceAll("\\)","");
Nisarg
  • 1,631
  • 6
  • 19
  • 31
1

You can try the following code:

String newUser = "NewUser123";
driver.findElement(By.xpath("//td[normalize-space(text())=" + newUser + "]/a")).click();
Jobin
  • 5,610
  • 5
  • 38
  • 53
0

In case if its a number in any loop table it can be written like

String sCol = "1";

driver.findElement(By.xpath("/html/body/div[1]/div[2]/div/div[2]/article/div/table/tbody/tr["+sRow+"]/td["+sCol+"]")).getText();

-1

Treat the xpath like any other string concatenation or interpolation you would do in Java

Robbie Wareham
  • 3,380
  • 1
  • 20
  • 38