Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/277.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 保存Web爬网结果(刮擦)_Python_Web Crawler_Scrapy - Fatal编程技术网

Python 保存Web爬网结果(刮擦)

Python 保存Web爬网结果(刮擦),python,web-crawler,scrapy,Python,Web Crawler,Scrapy,我已经编写了一个spider,它似乎运行正常,但我不确定如何保存它正在收集的数据 蜘蛛从开始,抓取主论坛页面,并为每个页面制作一个项目。然后,它继续浏览所有单独的论坛页面(同时传递项目),将每个线程的标题添加到匹配的论坛项目中。代码如下: from scrapy.spider import BaseSpider from scrapy.selector import HtmlXPathSelector from scrapy.contrib.linkextractors.sgml import

我已经编写了一个spider,它似乎运行正常,但我不确定如何保存它正在收集的数据

蜘蛛从开始,抓取主论坛页面,并为每个页面制作一个项目。然后,它继续浏览所有单独的论坛页面(同时传递项目),将每个线程的标题添加到匹配的论坛项目中。代码如下:

from scrapy.spider import BaseSpider
from scrapy.selector import HtmlXPathSelector
from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor
from scrapy.http import Request

from individualProject.items import ProjectItem

class TheScienceForum(BaseSpider):
    name = "TheScienceForum.com"
    allowed_domains = ["www.thescienceforum.com"]
    start_urls = ["http://www.thescienceforum.com"]
    
    def parse(self, response):
        Sel = HtmlXPathSelector(response)
        forumNames = Sel.select('//h2[@class="forumtitle"]/a/text()').extract()
        items = []
        for forumName in forumNames:
            item = ProjectItem()
            item['name'] = forumName
            items.append(item)
        

        forums = Sel.select('//h2[@class="forumtitle"]/a/@href').extract()
        itemDict = {}
        itemDict['items'] = items
        for forum in forums:
            yield Request(url=forum,meta=itemDict,callback=self.addThreadNames)  

    def addThreadNames(self, response):
        items = response.meta['items']
        Sel = HtmlXPathSelector(response)
        currentForum = Sel.select('//h1/span[@class="forumtitle"]/text()').extract()
        for item in items:
            if currentForum==item['name']:
                item['thread'] += Sel.select('//h3[@class="threadtitle"]/a/text()').extract()
        self.log(items)


        itemDict = {}
        itemDict['items'] = items
        threadPageNavs = Sel.select('//span[@class="prev_next"]/a[@rel="next"]/@href').extract()
        for threadPageNav in threadPageNavs:  
            yield Request(url=threadPageNav,meta=itemDict,callback=self.addThreadNames)
似乎因为我从不简单地返回对象(只产生新的请求),所以数据不会在任何地方持久存在。我尝试使用以下JSON管道:

class JsonWriterPipeline(object):

    def __init__(self):
        self.file = open('items.jl', 'wb')

    def process_item(self, item, spider):
        line = json.dumps(dict(item)) + "\n"
        self.file.write(line)
        return item
并使用以下命令运行spider:

scrapy crawl TheScienceForum.com -o items.json -t json
但到目前为止,一切都不起作用。我哪里会出错


欢迎任何想法或积极的批评。

您需要在至少一次回访中
产生项目。

@bornytm-

self.addThreadNames 
是要向其传递URL或中间结果的函数。如果要将其保存到csv或json文件中,可以执行以下操作

yield "result"  ("result" can be replaced with your variable to which you are storing data. If you have multiple value , use yield in for loop. )
之后

scrapy crawl TheScienceForum.com -o output.csv -t csv

这将帮助您

不需要任何额外的管道。Scrapy已经提供了存储项目的管道,默认格式是
jsonlines
,即每行一个json对象。因此,您只需要
-o
选项。主要的问题是:你在哪里返回项目?问题是,我希望最终得到的数据是,每个论坛都有一个JSON对象,其中包含论坛的标题,然后是所有的线程标题。如果我每次都生成一个项目,那么只有最后一次它才是完整的项目,对吗?当它包含所有数据时,您可以
生成项目。