【问题标题】:Limit how much elements scrapy can collect限制scrapy可以收集多少元素
【发布时间】:2015-06-19 14:58:46
【问题描述】:

我正在使用 scrapy 收集一些数据。我的 scrapy 程序在一次会话中收集了 100 个元素。我需要将其限制为 50 或任何随机数。我怎样才能做到这一点?欢迎任何解决方案。提前致谢

# -*- coding: utf-8 -*-
import re
import scrapy


class DmozItem(scrapy.Item):
    # define the fields for your item here like:
    link = scrapy.Field()
    attr = scrapy.Field()
    title = scrapy.Field()
    tag = scrapy.Field()


class DmozSpider(scrapy.Spider):
    name = "dmoz"
    allowed_domains = ["raleigh.craigslist.org"]
    start_urls = [
        "http://raleigh.craigslist.org/search/bab"
    ]

    BASE_URL = 'http://raleigh.craigslist.org/'

    def parse(self, response):
        links = response.xpath('//a[@class="hdrlnk"]/@href').extract()
        for link in links:
            absolute_url = self.BASE_URL + link
            yield scrapy.Request(absolute_url, callback=self.parse_attr)

    def parse_attr(self, response):
        match = re.search(r"(\w+)\.html", response.url)
        if match:
            item_id = match.group(1)
            url = self.BASE_URL + "reply/ral/bab/" + item_id

            item = DmozItem()
            item["link"] = response.url
            item["title"] = "".join(response.xpath("//span[@class='postingtitletext']//text()").extract())
            item["tag"] = "".join(response.xpath("//p[@class='attrgroup']/span/b/text()").extract()[0])
            return scrapy.Request(url, meta={'item': item}, callback=self.parse_contact)

    def parse_contact(self, response):
        item = response.meta['item']
        item["attr"] = "".join(response.xpath("//div[@class='anonemail']//text()").extract())
        return item

【问题讨论】:

    标签: python web-scraping web-crawler scrapy


    【解决方案1】:

    这就是 CloseSpider extensionCLOSESPIDER_ITEMCOUNT 设置的目的:

    指定项目数量的整数。如果蜘蛛刮伤 如果项目和那些项目被项目传递,则超过该金额 管道,蜘蛛会关闭的原因 closespider_itemcount。如果为零(或未设置),蜘蛛将不会关闭 按通过的项目数。

    【讨论】:

      【解决方案2】:

      我尝试了alecxe 的答案,但我必须结合所有 3 个限制才能使其正常工作,所以将其留在这里以防其他人遇到同样的问题:

      class GenericWebsiteSpider(scrapy.Spider):
          """This generic website spider extracts text from websites"""
      
          name = "generic_website"
      
          custom_settings = {
              'CLOSESPIDER_PAGECOUNT': 15,
              'CONCURRENT_REQUESTS': 15,
              'CLOSESPIDER_ITEMCOUNT': 15
          }
      ...
      

      【讨论】:

        猜你喜欢
        • 2017-09-28
        • 1970-01-01
        • 2018-04-01
        • 2017-03-19
        • 2015-05-18
        • 2016-07-21
        • 1970-01-01
        • 2016-10-15
        • 2012-01-08
        相关资源
        最近更新 更多