为什么我的数据无法保存为xls?
我用 scrapy 写了一个简单的网页爬虫,想把抓取到的数据保存到 .xls 文件里,因为我有一个现成的模块可以读取 xls 文件并对数据进行排序。但我遇到了一个看起来很傻的问题,就是怎么保存这个 .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')
但是无论我把这段代码放在哪里,打印出来的顺序总是: 创建 xls -> 初始化 xls -> 保存 xls -> 抓取并写入到 xls -> 关闭但没有保存。
我对开发还很陌生,遇到这个问题很困惑,任何建议我都会非常感激。
1 个回答
1
最好是创建一个自定义的项目处理类(可以看看scrapy的文档,里面有例子),然后把你所有写文件的代码放在这个类里。