我看到两件事:
-
a:nth-child(-n+3) 将选择 parent 元素的前 3 个子元素。
在您的情况下,它将选择所有 3 个 a 元素:前 2 个是 <div class="text"> 的孩子 1 和 2,最后一个是 <ins> 的第一个孩子
- 我认为
cssselect 没有正确翻译a:nth-child(-n+3),在an+b 形式中n 为负值(scrapy 在内部使用cssselect)
检查一下:
>>> cssselect.HTMLTranslator().css_to_xpath('a:nth-child(-n+3)')
u"descendant-or-self::*/*[name() = 'a' and ((position() -3) mod -1 = 0 and position() >= 3)]"
它应该类似于u"descendant-or-self::*/*[name() = 'a' and ((position() -3) mod -1 = 0 and position() <= 3)]"
我建议你使用 CSS 选择器和 XPath 的组合(你可以在 scrapy 中链接它们):
In [1]: import scrapy
In [2]: selector = scrapy.Selector(text="""
...: <td class="c3">
...: <div class="text">
...: <a class="title" href="https:// ">movie</a>
...: <a href="https:/ ">movieEN</a>
...: <p><ins><a hpp="thisweek-guide" href="https:// ">see more</a></ins></p>
...: </div>
...: </td>""")
In [3]: selector.css("td.c3 a:nth-child(-n+3)::text").extract()
Out[3]: []
In [4]: selector.css("td.c3").xpath("(.//a)[position() < last()]//text()").extract()
Out[4]: [u'movie', u'movieEN']
In [5]:
或者如果你只考虑<div class="text">的孩子:
In [8]: selector.css("td.c3 > * > a::text").extract()
Out[8]: [u'movie', u'movieEN']
In [9]: selector.css("td.c3 div.text > a::text").extract()
Out[9]: [u'movie', u'movieEN']