1

CSS/xpath selector to get the link text excluding the text in .muted.

I have html like this:

<a href="link">
          Text
   <span class="muted"> –text</span>
</a>

When I do getText(), I get the complete text like, Text-text. Is it possible to exclude the muted subclass text ?

Tried cssSelector = "a:not([span='muted'])" doesn't work.

xpath = "//a/node()[not(name()='span')][1]"

ERROR: The result of the xpath expression "//a/node()[not(name()='span')][1]" is: [objectText]. It should be an element.

2
  • 1
    cssSelector = "a span:not(.muted) should work Commented May 11, 2017 at 14:58
  • Thanks @winner_joiner. But this doesn't work. It returns an empty set. Commented May 11, 2017 at 17:23

2 Answers 2

2

AFAIK this cannot be done with CSS selector only. You can try to use JavaScriptExecutor to get required text.

As you didn't mention programming language you use I show you example on Python:

link = driver.find_element_by_css_selector('a[href="link"]')
driver.execute_script('return arguments[0].childNodes[0].nodeValue', link)

This will return just "Text" without " -text"

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you. This works but was looking if there is some other way as well. Probably using xpath selector or jquery ?
XPath to get required text is normalize-space(//a[@href="link"]/text()), but selenium doesn't support this syntax...
1

You cannot do this using Selenium WebDriver's API. You have to handle it in your code as follows:

// Get the entire link text
String linkText = driver.findElement(By.xpath("//a[@href='link']")).getText();

// Get the span text only
String spanText = driver.findElement(By.xpath("//a[@href='link']/span[@class='muted']")).getText();

// Replace the span text from link text and trim any whitespace
linkText.replace(spanText, "").trim();

1 Comment

Thanks. That helps.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.