如何从scrapy蜘蛛获取返回列表

时间:2020-02-22 01:09:27

标签: python-3.x scrapy

因此,我正在编写一个脚本来测试我的蜘蛛,但是我不知道如何在运行蜘蛛的脚本中捕获返回的数据。

我有这个return [self.p_name, self.price, self.currency]会在蜘蛛网的尽头返回。

在蜘蛛测试器中,我有以下脚本:

#!/usr/bin/python3
#-*- coding: utf-8 -*-

# Import external libraries
import scrapy
from scrapy.crawler import CrawlerProcess
from Ruby.spiders.furla import Furla

# Import internal libraries

# Variables

t = CrawlerProcess()

def test_furla():
    x = t.crawl(Furla, url='https://www.furla.com/pt/pt/eshop/furla-sleek-BAHMW64BW000ZN98.html?dwvar_BAHMW64BW000ZN98_color=N98&cgid=SS20-Main-Collection')
    return x

test_furla()
t.start()

它运行正常,唯一的问题是我不知道如何在测试人员那边获得回报。蜘蛛程序的输出为['FURLA SLEEK', '250.00', '€']

1 个答案:

答案 0 :(得分:1)

如果您需要访问蜘蛛收集的物品,我可能会使用signals来完成工作,特别是item_scraped信号。修改您的代码会像这样:

from scrapy import signals
# other imports and stuff

t = CrawlerProcess()

def item_scraped(item, response, spider):
    # do something with the item

def test_furla():
    # we need Crawler instance to access signals
    crawler = t.create_crawler(Furla)
    crawler.signals.connect(item_scraped, signal=signals.item_scraped)
    x = t.crawl(crawler, url='https://www.furla.com/pt/pt/eshop/furla-sleek-BAHMW64BW000ZN98.html?dwvar_BAHMW64BW000ZN98_color=N98&cgid=SS20-Main-Collection')
    return x

test_furla()
t.start()

其他信息可以在CrawlerProcess documentation中找到。另一方面,如果您需要处理Spider的全部输出,所有项目,则需要使用上述机制来累积项目,并在抓取完成后使用它们。