【问题标题】:CSS Selectors: select element where (parent|children) don't match XCSS选择器:选择(父|子)不匹配X的元素
【发布时间】:2011-05-23 16:08:18
【问题描述】:

我想选择一个没有特定类型子元素的元素,例如:

所有没有<table class="someclass">子元素的<li>元素,我只想选择父元素,不匹配表格的子元素。

同样,我想匹配其父元素不匹配 X 的元素,例如: 所有不是<table class="someclass"> 后代的<li> 元素。

我用的是python,还有lxml的cssselect。

谢谢!

【问题讨论】:

  • 我认为标准 CSS 选择器无法满足您的两个条件。

标签: python css css-selectors lxml


【解决方案1】:

CSS3 :not selector 将让您部分到达那里。不幸的是,there is no parent selector 所以你不能根据子元素的特征来选择元素。

对于您的第一个问题,您必须明确地进行遍历:

# All <li> elements who have no <table class="someclass"> children
[e.getparent() for e in CSSSelector('li > table:not(.someclass)')(html)]

# To make it unique if there could be multiple acceptable child tables
set(e.getparent() for e in CSSSelector('li > table:not(.someclass)')(html))

# If there could be empty <li>
set(itertools.chain(
    (e.getparent() for e in CSSSelector('li > table:not(.someclass)')(html)),
    CSSSelector('li:empty')(html)
))

单独的 CSS 选择器可以解决您的第二个问题:

# All <li> elements who are not descendents of <table class="someclass">
CSSSelector(':not(table.someclass) li')(html)

【讨论】:

    【解决方案2】:

    我不认为 CSS 选择器有“除了”选择,所以你不能那样做。也许你可以用 XPaths 做到这一点。更灵活,但即使那样你也会得到非常复杂和钝的路径表达式。

    我建议您简单地获取所有 &lt;li&gt; 元素,遍历每个子元素,如果其中一个子元素是表格,则跳过它。

    这将易于理解和维护,易于实施,除非您的性能要求非常极端并且您需要每秒处理数万页,否则它将足够快 (tm)。

    保持简单。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-04-12
      • 2015-09-12
      • 2010-12-04
      • 1970-01-01
      • 2020-03-06
      • 2015-02-03
      • 2016-06-09
      相关资源
      最近更新 更多