【问题标题】:Using scrapy selector with conditions使用带有条件的scrapy选择器
【发布时间】:2020-03-06 14:51:56
【问题描述】:

我正在使用“scrapy”来抓取一些文章,例如:https://fivethirtyeight.com/features/championships-arent-won-on-paper-but-what-if-they-were/
我在我的蜘蛛中使用以下代码:

    def parse_article(self, response):
       il = ItemLoader(item=Scrapping538Item(), response=response)
       il.add_css('article_text', '.entry-content *::text')

...这行得通。但我想让这个 CSS 选择器更复杂一点。 现在,我正在提取每个文本段落。但是看看这篇文章,里面有表格和可视化,其中也包括文本。 HTML 结构如下所示:

<div class="entry-content single-post-content">
    <p>text I want</p>
    <p>text I want</p>
    <p>text I want</p>
    <section class="viz">
        <header class="viz">
            <h5 class="title">TITLE-text</h5>
            <p class="subtitle">SUB-TITLE-text</p>
        </header>
        <table class="viz full"">TABLE DATA</table>
    </section>
    <p>text I want</p>
    <p>text I want</p>
</div>

使用上面的代码,我得到了类似的东西:

我想要的文字
我想要的文字
我想要的文字
TITLE-文本 SUB-TITLE-text 表数据 我想要的文字
我想要的文字

我的问题:

  • 如何修改add_css()函数,使其 获取除表格中的文本之外的所有文本?
  • 使用函数add_xpath会更容易吗?
  • 一般来说,最好的做法是什么? (提取文本 条件下)

非常感谢您的反馈

【问题讨论】:

    标签: python scrapy css-selectors web-crawler


    【解决方案1】:

    在您的 CSS 表达式中使用 &gt;limit it to children (direct descendants)

    .entry-content > *::text
    

    【讨论】:

      【解决方案2】:

      您可以使用 XPath 和 ancestor 轴获得所需的输出:

      '//*[contains(@class, "entry-content")]//text()[not(ancestor::*[@class="viz"])]'
      

      【讨论】:

        【解决方案3】:

        除非我错过了一些重要的东西,否则下面的 xpath 应该可以工作:

        import scrapy
        import w3lib
        
        raw = response.xpath(
            '//div[contains(@class, "entry-content") '
            'and contains(@class, "single-post-content")]/p'
        ).extract()
        

        这会省略表格内容,仅将段落中的文本和链接生成为列表。但是有一个问题!由于我们没有使用/text(),所以所有&lt;p&gt;&lt;a&gt; 标签仍然存在。让我们删除它们:

        cleaned = [w3lib.html.remove_tags(block) for block in raw] 
        

        【讨论】:

          猜你喜欢
          • 2014-02-06
          • 2021-07-13
          • 1970-01-01
          • 2015-02-23
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-07-17
          相关资源
          最近更新 更多