'What is use of '%s' in xpath

I have tried to know the reason in online but i didnt get it.

I want to know the reason why '%s' used in xpath instead of giving text message

I hope some one can help me on this.

see my scenario:
By.xpath(("//div[contains(text(),'%s')]/following-sibling::div//input"))



Solution 1:[1]

It's called wildcard.

E.g. you have

private final String myId = "//*[contains(@id,'%s')]";

private WebElement idSelect(String text) {
    return driver.findElement(By.xpath(String.format(myId, text)));
}

Then, you can make a function like:

public void clickMyId(idName){
   idSelect(idName.click();
}

And call

clickMyId('testId');

The overall goal of the %s is not using the string concatenation, but to use it injected into a string.

Solution 2:[2]

Sometimes, there are many locators for web elements which are of same kind, only they vary with a small difference say in index or String.

For e.g., //div[@id='one']/span[text()='Mahesh'] and

//div[@id='one']/span[text()='Jonny']

As it can been seen in the above example that the id is same for both the element but the text vary.

In that case, you can use %s instead of text. Like,

String locator = "//div[@id='one']//span[text()='%s']";

private By pageLocator(String name)

 {

  return By.xpath(String.format(locator, name));

}

So in your case,

By.xpath(("//div[contains(text(),'%s')]/following-sibling::div//input"))

the text is passed at runtime as only the text vary in the locator.

Solution 3:[3]

'%s' in XPath is used as String Replacement.

Example:

    exampleXpath = "//*[contains(@id,'%s')]"

void findElement(String someText)
{
    driver.findElement(By.xpath(String.format(exampleXpath, someText)));
}

So it will replace %s with someText passed by user.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Varun
Solution 3 Bharat Mane