0

I am trying to grab one or more table cells that contain a particular string. I am not able to accomplish this with

var tableCells = table.FindElements(By.CssSelector("td:contains('my partial text')"));  

What is the correct css selector text to use here?

I've also tried the following:

var tableCells = table.FindElements(By.TagName("td")).Where(tableCell => tableCell.Contains("my partial text"));

but it is extremely slow.

1 Answer 1

1

There is no such CSS selector as :contains(). It was a proposal that was discarded years ago.

The reason table.FindElements(By.TagName("td")).Where(tableCell => tableCell.Contains("my partial text")); is slow should be at least partly obvious - you're asking WebDriver to find every table cell in the document, and then iterate over them all.

You can do this much more efficiently using an XPath locator, something like table.FindElements(By.xpath("//td[contains(.,'my partial text')]")). This is exactly what it looks like - the XPath equivalent of your attempted CSS locator.

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

6 Comments

Hey, thanks for the response. I read that css selector is more efficient than xpath. Is that your impression? Should I generally stick with css selector and only use xpath when there isn't an equivalent like with this example?
"I read that css selector is more efficient than xpath." - the only reason to have css selectors instead of xpath is the fact that for previous selenium versions (Selenium RC) XPath was extremely slow in IE. For now you can freely use XPath.
@IgorKhrol is correct. Benchmarks have proved that XPath and CSS are similarly efficient in WebDriver.
At the risk of being pedantic, I have to point out that XPath selectors in some versions of IE can still be dramatically slower than comparable CSS selectors. This IE performance discrepancy is not limited to RC; it affects WebDriver as well.
I know better than to argue with @JimEvans on this. Nobody knows the WebDriver IE code better than Jim - he wrote it. I read another WebDriver committer making claims of nearly-equivalent performance for CSS and XPath, but those may have only been for recent IE version.
|

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.