2010-12-10 74 views
0

我想选择哪一个没有孩子的特定类型的元素,例如:CSS选择:选择的元素在哪里(父|孩子)不匹配X

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

在类似的笔记上,我想匹配父母不匹配X的元素,例如: 全部<li>元素不是<table class="someclass">的后代。

我正在使用python和lxml的cssselect。

谢谢!

+2

我认为既不是你的条件也可以与标准得到满足CSS选择器。 – Gumbo 2010-12-10 18:56:00

回答

0

我不认为CSS选择器有“任何东西,但”选择,所以你不能这样做。也许你可以用XPath做到这一点。它们更加灵活,但即使如此,你也会得到非常复杂和钝的路径表达式。

我建议你简单地得到所有<li>元素,通过每个元素的孩子,并跳过它,如果其中一个孩子是一张桌子。

这将很容易理解和维护,易于实现,除非您的性能要求非常高,而且您需要每秒处理数万页,否则它将达到快速(tm)。

保持简单。

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)