johan.i.zahri
johan.i.zahri

Reputation: 316

How to extract tags with content that have certain substring using CSS selectors?

I have the following HTML:

<tr bgcolor="#DEDEDE">
    <td>
        <b>OK:Have idea</b>
    </td>
    <td>
        <b>KO:Write code</b>
    </td>
    <td>
        <b>KO:Run code</b>
    </td>
    <td>
        <b>KO:Debug code</b>
    </td>
</tr>

I want to extract the following:

<b>KO:Write code</b>
<b>KO:Run code</b>
<b>KO:Debug code</b>

By the substring KO:. How do I do it using CSS selector expressions?

Upvotes: 0

Views: 910

Answers (1)

BoltClock
BoltClock

Reputation: 723739

You can use :contains() which was dropped from the CSS3 spec but is implemented by Selenium:

WebDriver.findElements(By.cssSelector("td b:contains('KO:')"));

There is no equivalent pseudo-class for starts-with or ends-with, though, so :contains() is the furthest you can go with a CSS locator. If you need to filter only by starting with the substring KO:, you should use an XPath locator:

WebDriver.findElements(By.xpath("//td/b[starts-with(text(), 'KO:')]"));

Upvotes: 2

Related Questions