RASHI
RASHI

Reputation: 3

How can I pass variable in xpath from the script?

WebElement selectRadioButton;

public void selectContractType(String txt)
    {
        selectRadioButton.sendKeys(txt);
        selectRadioButton.click();
    }

Tried like below,

 @FindBy(xpath="//*[@class='example-radio-button mat-radio-button mat-accent'][@value='"+txt+"']")

But getting error like this

Upvotes: 0

Views: 915

Answers (3)

Nandan A
Nandan A

Reputation: 2922

You cannot parametrize the WebElement which was denoted by @FindBy annotation. @FindBy annotation purpose is to initialize the elements while initializing the class as part of PageFactory. You need to do something like below,

Call this below into your method.

WebElement element = createWebElement("//*[@class='example-radio-button mat-radio-button mat-accent'][@value="+txt+"]");

Keep the below reusable method in Utility.

public static WebElement createWebElement(String elementText) {
    WebElement element = null;
    try {
        WebDriverWait wait = new WebDriverWait(driver, 10);
        wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(elementText)));
        element = driver.findElement(By.xpath(elementText));
    } catch (Exception e) {
        System.out.println("Exception occurred: " + e);
    }
    return element;
}

Keep

WebElement element = createWebElement("//*[@class='example-radio-button mat-radio-button mat-accent'][@value="+txt+"]");

inside selectContractType() method and assign some value to String txt;

Upvotes: 1

Mayank Shukla
Mayank Shukla

Reputation: 302

Well for such cases, I would suggest you to make use of Format Specifier.

For example:

String txt = "someValue";
String radioButtonLocator = String.format("//*[@class='example-radio-button mat-radio-button mat-accent' and @value='%s']", txt);
WebElement radioButton = driver.findElement(By.xpath(radioButtonLocator));

Is this what you are looking for?

Upvotes: 0

Dora
Dora

Reputation: 191

@FindBy(xpath="//*[@class='example-radio-button mat-radio-button mat-accent'][@value="+txt+"]")

This should work if you want to pass txt string to @value.

Upvotes: 0

Related Questions