我用scrapy写了一个非常简单的网络刮刀。我想将已删除的数据保存到.xls文件,因为我有一个现有的模块来读取xls并对已删除的数据进行排序。但是我发现了一个愚蠢的绊脚石,实际上是在保存.xls。
然而,无论我把保存声明放在哪里,它似乎都会在之前保存实际的网页抓取开始。离开我初始化(第一行填写标题),但否则为空电子表格。这就是我所拥有的(删除网站以保存无辜的服务器)
# encoding=utf-8
from scrapy.contrib.spiders import CrawlSpider, Rule
from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor
from scrapy.selector import HtmlXPathSelector
from scrapy.item import Item, Field
from xlwt import Workbook
# Working row on new spreadsheet
row_number = 0
# Create new spreadsheet
newDb = Workbook(encoding='utf-8')
newFile = newDb.add_sheet('Sheet1')
values = ['product','description','image']
class TestSpider(CrawlSpider):
# Initiate new spreadsheet
global newFile
global values
global row_number
for cell in range (len(values)):
newFile.write(row_number, cell, values[cell])
row_number = row_number + 1
# Initiate Spider
name = "Test"
allowed_domains = []
start_urls = ["http://www.website.to/scrape",]
rules = (Rule(SgmlLinkExtractor(restrict_xpaths="//div[@class='content']/h3"), callback='parse_product'),)
def parse_product(self, response):
hxs = HtmlXPathSelector(response)
item = TestItem()
item['product'] = hxs.select('//div [@class = "col-right"][1]/table/tr[1]/td/text()').extract()
item['description'] = hxs.select('//div[@class="columns"][1]/div [@class = "col-right"]/p/text()' ).extract()
item['image'] = hxs.select('//img /@src').extract()
global values
global newFile
global row_number
# This is where products are written to the xls
for title in values:
# test to increase row_number, at the start of each new product
if title == "product":
row_number = row_number + 1
try:
newFile.write(row_number, values.index(title), item[title] )
except:
newFile.write(row_number, values.index(title), '')
class TestItem(Item):
product = Field()
description = Field()
image = Field()
我认为我说的只是需要添加
global newDb
newDb.save('./products_out.xls')
在正确的位置,但是再次,似乎无论我在哪里添加它,print语句表明操作的顺序始终是: 创建xls - >初始化xls - >保存xls - >刮写并写入xls - >关闭而不保存。
我对发展很陌生,我对此感到茫然,任何建议都会感激不尽。
答案 0 :(得分:1)
理想情况下,您应该创建一个自定义项管道类(查看示例的scrapy文档)并将所有文件编写代码放在那里。