Home > database >  How can I pass variable in xpath from the script?
How can I pass variable in xpath from the script?

Time:11-15

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

CodePudding user response:

@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.

CodePudding user response:

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;
}

CodePudding user response:

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?

  • Related