我写了一个似乎运行正常的蜘蛛,但我不确定如何保存它正在收集的数据。
蜘蛛从TheScienceForum开始,抓住主论坛页面并为每个页面制作一个项目。然后它继续浏览所有单独的论坛页面(随之传递项目),将每个线程的标题添加到匹配的论坛项目。代码如下:
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
并使用以下内容运行蜘蛛:
scrapy crawl TheScienceForum.com -o items.json -t json
但到目前为止没有任何工作。我哪里可能出错?
热烈欢迎任何想法或积极批评。
答案 0 :(得分:2)
至少在一个回调中你需要yield item
。
答案 1 :(得分:1)
@bornytm -
self.addThreadNames
是您传递网址或中间结果的函数。如果要将其保存到文件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
这会对你有所帮助