Home > Blockchain >  Using Selenium and Java How to ignore part of an element in xpath
Using Selenium and Java How to ignore part of an element in xpath

Time:12-29

I have the method below:

}
protected String getCertID() {
    String certIDKey = "certID";
    TestAction action = new TestAction(ActionType.SET_ELEMENT_TEXT,springContext);

    action.setIdentifierType("xpath");
    action.setIdentifierValue("//h1[contains(@data-id,'header_title')]");
    action.setValue(certIDKey);

    action.perform(driverFactory,testContext);

    log.info("CertID: "   testContext.getVariable(certIDKey));
    return testContext.getVariable(certIDKey);
}

This method returns this value: 21/2/467092- Saved

I require the method to return only: 21/2/467092 and ignore the - Saved part of element returned

CodePudding user response:

If h1 contain child elements, e.g. some span elements, and the exact text you want to get placed in some child element, like:

<h1 data-id="header_title">
    <span id="data">21/2/467092</span>
    <span>- Saved</span>
</h1>

you can use

"//h1[contains(@data-id,'header_title')]/span[1]"

or

"//h1[contains(@data-id,'header_title')]/span[@id='date']"

Otherwise, for case:

<h1 data-id="header_title">21/2/467092- Saved</h1>

or

<h1 data-id="header_title">
    21/2/467092
    <span>- Saved</span>
</h1>

you can only adjust the result text of h1

...
String roughText = testContext.getVariable(certIDKey);
return roughText.split("-")[0].trim();

CodePudding user response:

If the "- Saved" is constant there, you can just replace it with "" :

return testContext.getVariable(certIDKey).replace("- Saved", "")
  • Related