【问题标题】:css or xpath :select the first 2 elementscss 或 xpath :选择前 2 个元素
【发布时间】:2014-09-14 06:47:46
【问题描述】:

我在练习Scrapy,想问一个问题:

我要废弃的网站结构如下:

<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>

但我只想要前 2 个 href 元素(movie 和 MovieEN),没有最后一个(查看更多) 我该怎么办?
这是我的代码,但不起作用

ssel.css("td.c3 a:nth-child(-n+3)::text").extract()

【问题讨论】:

    标签: python xpath css-selectors scrapy


    【解决方案1】:

    我看到两件事:

    • a:nth-child(-n+3) 将选择 parent 元素的前 3 个子元素。

    在您的情况下,它将选择所有 3 个 a 元素:前 2 个是 &lt;div class="text"&gt; 的孩子 1 和 2,最后一个是 &lt;ins&gt; 的第一个孩子

    • 我认为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() &lt;= 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]: 
    

    或者如果你只考虑&lt;div class="text"&gt;的孩子:

    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']
    

    【讨论】:

      猜你喜欢
      • 2021-12-22
      • 2020-03-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-21
      • 1970-01-01
      相关资源
      最近更新 更多