因此,当我将其导出为 XML 时,我试图将使用 Scrapy 从网站上抓取的数据导出为特定格式。
这是我希望我的 XML 的样子:
<?xml version="1.0" encoding="UTF-8"?>
<data>
<row>
<field1><![CDATA[Data Here]]></field1>
<field2><![CDATA[Data Here]]></field2>
</row>
</data>
我正在使用以下命令运行我的抓取:
$ scrapy crawl my_scrap -o items.xml -t xml
我得到的当前输出大致如下:
<?xml version="1.0" encoding="utf-8"?>
<items><item><field1><value>Data Here</value></field1><field2><value>Data Here</value></field2></item>
如您所见,它正在添加<value>
字段,我无法重命名根节点或项目节点。我知道我需要使用XmlItemExporter,但我不确定如何在我的项目中实现它。
我已尝试将其添加到pipelines.py
此处,但我总是以错误告终:
AttributeError: 'CrawlerProcess' object has no attribute 'signals'
有没有人知道在使用 ? 将数据导出到 XML 时如何重新格式化数据的示例XmlItemExporter
?
编辑:
在我的模块中显示我的 XmlItemExporter piplines.py
:
from scrapy import signals
from scrapy.contrib.exporter import XmlItemExporter
class XmlExportPipeline(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):
file = open('%s_products.xml' % spider.name, 'w+b')
self.files[spider] = file
self.exporter = XmlItemExporter(file)
self.exporter.start_exporting()
def spider_closed(self, spider):
self.exporter.finish_exporting()
file = self.files.pop(spider)
file.close()
def process_item(self, item, spider):
self.exporter.export_item(item)
return item
编辑(显示修改和追溯):
我修改了spider_opened
功能:
def spider_opened(self, spider):
file = open('%s_products.xml' % spider.name, 'w+b')
self.files[spider] = file
self.exporter = XmlItemExporter(file, 'data', 'row')
self.exporter.start_exporting()
我得到的追溯是:
Traceback (most recent call last):
File "/root/self_opportunity/venv/lib/python2.6/site-packages/twisted/internet/defer.py", line 551, in _runCallbacks
current.result = callback(current.result, *args, **kw)
File "/root/self_opportunity/venv/lib/python2.6/site-packages/scrapy/core/engine.py", line 265, in <lambda>
spider=spider, reason=reason, spider_stats=self.crawler.stats.get_stats()))
File "/root/self_opportunity/venv/lib/python2.6/site-packages/scrapy/signalmanager.py", line 23, in send_catch_log_deferred
return signal.send_catch_log_deferred(*a, **kw)
File "/root/self_opportunity/venv/lib/python2.6/site-packages/scrapy/utils/signal.py", line 53, in send_catch_log_deferred
*arguments, **named)
--- <exception caught here> ---
File "/root/self_opportunity/venv/lib/python2.6/site-packages/twisted/internet/defer.py", line 134, in maybeDeferred
result = f(*args, **kw)
File "/root/self_opportunity/venv/lib/python2.6/site-packages/scrapy/xlib/pydispatch/robustapply.py", line 47, in robustApply
return receiver(*arguments, **named)
File "/root/self_opportunity/self_opportunity/pipelines.py", line 28, in spider_closed
self.exporter.finish_exporting()
exceptions.AttributeError: 'XmlExportPipeline' object has no attribute 'exporter'