Ip Man
Ip Man

Reputation: 77

Getting text of the element with additional tags inside via selenium

I want to get text inside of 'a' tag, but it has 'i' tag with its own text also.
How to filter out 'i' tag text from 'a'? Text inside of 'i' might be different.

enter image description here

I used findElement() with //div[@class='cart-content-btn']//a/i/following-sibling::node() but it returns the exception below.

invalid selector: The result of the xpath expression is: [object Text]. It should be an element.

How to bypass it to get text without 'i' tag text?

Upvotes: 1

Views: 627

Answers (1)

Prophet
Prophet

Reputation: 33351

You can get the text content of a parent a element and then to reduce the i child element text from it, as following:

String entireText = driver.findElement(By.xpath("//div[@class='cart-content-btn']//a")).getText().trim();
String iElementText =driver.findElement(By.xpath("//div[@class='cart-content-btn']//a/i")).getText().trim();
String parentTextOnly = entireText.replace(iElementText, "").trim();

I've added .trim() to remove possible leading or trailing spaces.

Upvotes: 1

Related Questions