2010-12-10 72 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)