Reputation: 11
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"))
Upvotes: 1
Views: 14309
Reputation: 238
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.
Upvotes: 1
Reputation: 296
'%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.
Upvotes: 0
Reputation: 3461
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.
Upvotes: 1