如何在Scrapy处理完所有URL后存储累计数据?

1 投票
1 回答
594 浏览
提问于 2025-04-18 03:56

我正在尝试在Scrapy完成工作后存储一些数据(也就是说,在它处理完我要求的每个网址后)。每当Scrapy解析出一些结果(通过爬虫类中的解析函数),我就会把一些信息添加到类中的一个全局对象里。我希望在最后能访问到这个对象,并且如果可能的话,想通过一个Python脚本来完成这件事。以下是我的爬虫代码:

from scrapy.spider import Spider
from scrapy.selector import Selector
from nltk.corpus import stopwords


from newsScrapy.items import NewsscrapyItem

class newsScrapySpider(Spider):
    name = "newsScrapy"
    start_urls = []

    global wordMatrix
    wordMatrix = {}

    global prefix
    prefix = "http://www.nytimes.com/indexes/"
    sufix = "/todayspaper/index.html"
    for year in range (2000,2015):
        for month in range (1,13):
            for day in range (1,32):
                if(month<10 and day<10):
                    start_urls.append (prefix+str(year)+"/"+"0"+str(month)+"/"+"0"+str(day))
                elif (month<10 and day>9):
                    start_urls.append (prefix+str(year)+"/"+"0"+str(month)+"/"+str(day))
                elif (month>9 and day<10):
                    start_urls.append (prefix+str(year)+"/"+str(month)+"/"+"0"+str(day))
                else:
                    start_urls.append (prefix+str(year)+"/"+str(month)+"/"+str(day))

    def parse(self, response):
        sel = Selector(response)
        items = []
        text = sel.xpath('//body//text()').re('(\w+)')

        item = NewsscrapyItem()

        item['body'] = text
        item['date'] = response.url.strip(prefix)

        items.append(item)

        for word in item['body']:
            word = word.strip(' ').strip(',').strip('\n')
            word = word.lower()
            if (not word in stopwords.words('english')):
                if(wordMatrix.__contains__((word, item['date']))):
                    wordMatrix[word,item['date']]+=1
                else:
                    wordMatrix[word, item['date']]=1


        # print wordMatrix
        return items

我的想法是,在抓取结束后(也就是所有数据都收集完毕后),访问wordMatrix这个变量,并且希望能从另一个Python脚本中做到这一点(比如用来绘图)。非常感谢!

1 个回答

0

和你现有的导入代码一起:

try:
    import cPickle as pickle
except ImportError:
    import pickle

然后就在 return items 之前:

pickle.dump(wordMatrix, '/path/to/file/wordMatrix.data');

在另一个脚本中,你可以用以下方式加载这些数据:

try:
    import cPickle as pickle
except ImportError:
    import pickle

wordMatrix = pickle.load('/path/to/file/wordMatrix.data')

Pickling 是一种将任何 Python 对象转换成可以存储或传输的格式的过程,称为序列化;而将这种格式再转换回 Python 对象的过程叫做反序列化。Python 标准库中有两个实现:pickle 是用纯 Python 写的,而 cPickle 是用 C 语言写的,所以速度更快。这个不太常见的导入代码试图导入更快的那个,但比如说 IronPython 就没有 cPickle,所以在这种情况下就会导入后者。两个模块的功能完全相同,并且使用的接口也一样。

撰写回答