2

I want to find elements by css selector, but I want to skip some of them, how can I do it?

driver.FindElements(By.CssSelector("a[href]")) 

but I need not to take href that has logoff and client/contract in it

safary
  • 325
  • 2
  • 7
  • 26

2 Answers2

2

You probably don't need LINQ for this. You can use the :not() pseudo-class, one for each value you want to exclude (note the *= in each negation; I'm assuming substring matches here):

driver.FindElements(By.CssSelector("a[href]:not([href*='logoff']):not([href*='client'])"))

An exception is if you have a dynamic list of values that you want to exclude: you can either build your selector programmatically using string.Join() or a loop and then pass it to By.CssSelector(), or you can follow Richard Schneider's answer using LINQ to keep things clean.

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
1

After using CSS to get the elements then use LINQ to filter on the href.

Using System.Linq;

string[] blackList = new string[] { "logoff, "client",... };
string[] urls = driver
  .FindElements(By.CssSelector("a[href]"))
  .Select(e => e.GetAttribute("href"))
  .Where(url => !blackList.Any(b => url.Contains(b)))
  .ToArray();

Checking the URL is case-sensitive, because that is what W3C states. You may want to change this.

Community
  • 1
  • 1
Richard Schneider
  • 34,944
  • 9
  • 57
  • 73