当我从命令行运行它时,我的scraper工作正常,但是当我尝试从python脚本内运行它时(使用Twisted方法概述here)它不输出它通常所做的两个CSV文件。我有一个管道创建和填充这些文件,其中一个使用CsvItemExporter(),另一个使用writeCsvFile()。下面是代码:从Python脚本内部运行scrapy - CSV导出器不起作用
class CsvExportPipeline(object):
def __init__(self):
self.files = {}
@classmethod
def from_crawler(cls, crawler):
pipeline = cls()
crawler.signals.connect(pipeline.spider_opened, signals.spider_opened)
crawler.signals.connect(pipeline.spider_closed, signals.spider_closed)
return pipeline
def spider_opened(self, spider):
nodes = open('%s_nodes.csv' % spider.name, 'w+b')
self.files[spider] = nodes
self.exporter1 = CsvItemExporter(nodes, fields_to_export=['url','name','screenshot'])
self.exporter1.start_exporting()
self.edges = []
self.edges.append(['Source','Target','Type','ID','Label','Weight'])
self.num = 1
def spider_closed(self, spider):
self.exporter1.finish_exporting()
file = self.files.pop(spider)
file.close()
writeCsvFile(getcwd()+r'\edges.csv', self.edges)
def process_item(self, item, spider):
self.exporter1.export_item(item)
for url in item['links']:
self.edges.append([item['url'],url,'Directed',self.num,'',1])
self.num += 1
return item
这里是我的文件结构:
SiteCrawler/ # the CSVs are normally created in this folder
runspider.py # this is the script that runs the scraper
scrapy.cfg
SiteCrawler/
__init__.py
items.py
pipelines.py
screenshooter.py
settings.py
spiders/
__init__.py
myfuncs.py
sitecrawler_spider.py
刮板似乎在其他方面正常。命令行末尾的输出表明预期的页面数已被抓取,并且蜘蛛似乎正常完成。我没有收到任何错误消息。
---- 编辑: ----
装入打印语句和语法错误进入管道没有任何效果,所以会出现这条管道被忽略。为什么会这样呢?
下面是脚本运行刮刀(runspider.py)代码:
from twisted.internet import reactor
from scrapy import log, signals
from scrapy.crawler import Crawler
from scrapy.settings import Settings
from scrapy.xlib.pydispatch import dispatcher
import logging
from SiteCrawler.spiders.sitecrawler_spider import MySpider
def stop_reactor():
reactor.stop()
dispatcher.connect(stop_reactor, signal=signals.spider_closed)
spider = MySpider()
crawler = Crawler(Settings())
crawler.configure()
crawler.crawl(spider)
crawler.start()
log.start(loglevel=logging.DEBUG)
log.msg('Running reactor...')
reactor.run() # the script will block here until the spider is closed
log.msg('Reactor stopped.')
这些文件可以写在别的地方吗? 你能检查你的输出文件路径或使用绝对文件路径吗? –
@pault。好点子。我现在使用os.path.dirname(__ file__),getcwd()和输入的确切文件路径来尝试它。不幸的是,这些没有任何区别。 – jkdune
我试着添加打印语句来显示什么getcwd()和os.path.dirname(文件)输出,但他们似乎并没有执行。这是否意味着管道被忽略?或者是在反应堆内部运行,干扰我的打印? – jkdune