我想选择一个没有特定类型子元素的元素,例如:
所有没有<li>子元素的<table class="someclass">元素,我只想选择父元素,而不是不匹配表的子元素。
同样,我希望匹配父元素与X不匹配的元素,例如:所有不是<li>后代的<table class="someclass">元素。
我使用python和lxml的cssselect。
谢谢!
发布于 2010-12-10 22:19:03
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)发布于 2010-12-10 21:03:31
我不认为CSS选择器有“除了”选择,所以你不能这样做。也许你可以用XPaths来做。这更灵活,但即使这样,您也会得到非常复杂和迟钝的路径表达式。
我建议您只需获取所有的<li>元素,遍历每个元素子元素,如果其中一个子元素是表,则跳过它。
这将很容易理解和维护,易于实现,除非您的性能要求非常极端,并且您需要每秒处理数万页,否则它将足够快(tm)。
保持简单。
https://stackoverflow.com/questions/4412253
复制相似问题