【问题标题】:Activating a Pipeline Component in Scrapy to write JSON在 Scrapy 中激活管道组件以编写 JSON
【发布时间】:2020-03-12 12:28:32
【问题描述】:

我正在尝试将抓取的项目保存在单独的 json 文件中,但我没有看到任何输出文件。管道和项目在 scrapy 项目文件夹中的 piplines.py 和 items.py 文件中定义。我必须显式调用 process_item() 还是在我在 scrape() 中返回项目时自动调用它?我在 CrawlerProcess(settings={'ITEM_PIPELINES'}) 中启用了管道。谢谢。

管道

import json,datetime

class JsonWriterPipeline(object):
    def process_item(self, item, spider):
        # return item
        fileName = datetime.datetime.now().strftime("%Y%m%d%H%M%S") + '.json'
        try:
            with open(fileName,'w') as fp:
                json.dump(dict(item),fp)
                return item
        except:
            return item
class ProjectItem(scrapy.Item):
   title = scrapy.Field()
   url = scrapy.Field()
class mySpider(CrawlSpider):
   name = 'mySPider'
   allowed_domains = ['allowedDOmain.org']
   start_urls = ['https://url.org']

def parse(self,response):
        monthSelector = '//div[@class="archives-column"]/ul/li/a[contains(text(),"November 2019")]/@href'
        monthLink = response.xpath(monthSelector).extract_first()
        yield response.follow(monthLink,callback=self.scrape)

def scrape(self,response):
        # get the links to all individual articles
        linkSelector = '.entry-title a::attr(href)'
        allLinks = response.css(linkSelector).extract()

        for link in allLinks:
            # item = articleItem()
            item = ProjectItem()
            item['url'] = link
            request = response.follow(link,callback=self.getContent)
            request.meta['item'] = item
            item = request.meta['item']
            yield item

        nextPageSelector = 'span.page-link a::attr(href)'
        nextPageLink = response.css(nextPageSelector).extract_first()
        yield response.follow(nextPageLink,callback=self.scrape)

def getContent(self,response):
        item = response.meta['item']
        TITLE_SELECTOR = '.entry-title ::text'
        item['title'] = response.css(TITLE_SELECTOR).extract_first()
        yield item

【问题讨论】:

  • 在settings.py中,有没有把JsonWriterPipeline类添加到ITEMPIPELINES中?
  • 是的,我做了但没有工作。
  • 你从哪里调用scrape函数?这通常在蜘蛛类中完成。你能发布整个课程吗?
  • 是的,scrape 函数与 getContent 和 parse 一起位于蜘蛛类中。
  • 添加了蜘蛛类(parse、getContent 和 scrape 函数在源文件中正确缩进)。

标签: python web-scraping scrapy web-crawler


【解决方案1】:

在 settings.py 中添加:

ITEM_PIPELINES = {
        'myproject.pipelines.JsonWriterPipeline':100
}

其中 myproject 是您的项目/文件夹的名称。

查看本页最后一个标题:https://docs.scrapy.org/en/latest/topics/item-pipeline.html

【讨论】:

    【解决方案2】:

    在脚本中运行爬虫时,需要使用下面描述的方法导入设置。 Running scrapy from script not including pipeline

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-03-11
      • 1970-01-01
      • 2020-07-30
      • 1970-01-01
      • 2015-07-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多