【问题标题】: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。
谢谢!
【问题讨论】:
标签:
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 做到这一点。更灵活,但即使那样你也会得到非常复杂和钝的路径表达式。
我建议您简单地获取所有 <li> 元素,遍历每个子元素,如果其中一个子元素是表格,则跳过它。
这将易于理解和维护,易于实施,除非您的性能要求非常极端并且您需要每秒处理数万页,否则它将足够快 (tm)。
保持简单。