【问题标题】:How to use css selector with "not" in c#?如何在c#中使用带有“not”的css选择器?
【发布时间】:2015-12-25 07:37:38
【问题描述】:

我想通过css选择器查​​找元素,但是我想跳过其中一些,我该怎么做?

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

但我不需要使用其中包含注销和客户端/合同的 href

【问题讨论】:

  • 你真的不需要 LINQ。只需使用 :not() 伪。阅读它。
  • 但是如果我想跳过不止一件事会怎样?像“a[href]:not(apple orbanana)”
  • 如果是not(apple or banana),那么它既是not(apple)又是not(banana),因此是:not(apple):not(banana)

标签: c# selenium-webdriver css-selectors


【解决方案1】:

您可能不需要 LINQ。您可以使用:not() 伪类,一个用于您要排除的每个值(注意每个否定中的*=;我假设这里的子字符串匹配):

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

如果您有要排除的值的动态列表,则例外:您可以使用string.Join() 或循环以编程方式构建选择器,然后将其传递给By.CssSelector(),或者您可以按照Richard Schneider 的回答使用 LINQ 保持整洁。

【讨论】:

    【解决方案2】:

    使用 CSS 获取元素后,使用 LINQ 过滤 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();
    

    检查 URL 区分大小写,因为那是 W3C states。您可能需要更改此设置。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-16
      • 2019-08-03
      • 2016-09-05
      相关资源
      最近更新 更多