【问题标题】:How to increment a counter in spider if condition in pipelines is True ? [SCRAPY-PYTHON]如果管道中的条件为 True ,如何在蜘蛛中增加计数器? [SCRAPY-Python]
【发布时间】:2020-04-22 10:27:19
【问题描述】:

我正在抓取物品并在网址中使用邮政编码 (cp)

def parse(self, response):
    liste = ['09', '81']
    for counter in range(len(liste)):
        cp = liste[counter]
        for i in range(0, 2):
            user_agent = random.choices(user_agent_list)
            headers = {

                'User-Agent': str(user_agent),
                "Connection": "close",
            }

         next_pagination_link ='https://www.seloger.com/list.htm?projects=2&types=1,2&places=[{cp:' + 
                               str(cp) + '}]&sort=d_dt_crea&enterprise=0&qsVersion=1.0&LISTING- 
                               LISTpg=' + str(i) + ''

在 pipilines.py 中,我在 process_item 方法中使用这个脚本来删除 sql 数据库中的现有项目:

    if record is None:
        print('storing item')
        self.store_db(item)
        return True
    elif record is not None:
        raise DropItem("Item already exists: %s" % item['lien_du_bien'])

我想要做的是:如果一个项目被丢弃,我想将蜘蛛中的变量计数器增加 1,以便移动到另一个邮政编码。

有没有办法做到这一点?

【问题讨论】:

  • 你可以通过process_item(self, item, spider)方法访问蜘蛛

标签: python web-scraping scrapy web-crawler pipeline


【解决方案1】:

在你的管道def process_item(self, item, spider) 中,你可以通过spider.YOUR_SPIDER_VARIABLE 访问你的 Spider 的任何变量

def process_item(self, item, spider):
    if record is None:
        print('storing item')
        self.store_db(item)
        return True
    elif record is not None:
        spider.VARIABLE_TO_INCREMENT
        raise DropItem("Item already exists: %s" % item['lien_du_bien'])

【讨论】:

    猜你喜欢
    • 2015-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-04
    • 1970-01-01
    • 2015-10-02
    • 1970-01-01
    相关资源
    最近更新 更多