CSV 导出不起作用

CSV export is not working

这是我的蜘蛛class:

import scrapy
from scrapy.spiders import CrawlSpider, Rule
from scrapy.selector import HtmlXPathSelector
from scrapy.http.request import Request
from scrapy.crawler import CrawlerProcess
from scrapy.linkextractors.sgml import SgmlLinkExtractor
import csv

class StackItem(scrapy.Item):

    job_role = scrapy.Field()
    company = scrapy.Field()
    location = scrapy.Field()
    desc = scrapy.Field()
    read_more = scrapy.Field()


class newJobSpider(CrawlSpider):

    name = "newFlaskSpider"
    allowed_domains = ["placementindia.com"]
    start_urls = ["http://jobs.placementindia.com/lucknow"]
    rules = (Rule (SgmlLinkExtractor(allow=('.*\?id1=.*',),restrict_xpaths=('//a[@class="prevNext next"]',))
, callback="parse_items", follow= True),)

    def parse_items(self, response):
        hxs = HtmlXPathSelector(response)
        posts = hxs.select("//article[@class='classified']")
        items = []

        for post in posts:
            item = StackItem()
            item["job_role"] = post.select("div[@class='uu mb2px']/a/strong/text()").extract()
            item["company"] = post.select("p[1]/text()").extract()
            item["location"] = post.select("p[@class='mb5px b red']/text()").extract()
            item["desc"] = post.select("details[@class='aj mb10px']/text()").extract()
            item["read_more"] = post.select("div[@class='uu mb2px']/a/@href").extract()enter code here
            items.append(item)

            for item in items:
                yield item

这是项目管道

class myExporter(object):

    def __init__(self):
        self.myCSV = csv.writer(open('output6.csv', 'wb'))
        self.myCSV.writerow([item['job_role'], item['company'], item['location'], item['desc'], item['read_more']])

    def process_item(self, item, spider):
        self.myCSV.writerow([item['job_role'], item['company'], item['location'], item['desc'], item['read_more']])

        return item   

当它们分开 class、运行 时很好。我在 csv 文件中得到结果。由于我的项目要求,我需要蜘蛛定义中的 csv 导出器 class。这些class怎么组合??

这个问题有两种解决方法:

1) 为什么要嵌套一个 class?

如果您必须将导出器嵌套在蜘蛛 class 本身中,则不应嵌套。并且不需要单独的出口商。因为如果你嵌套了导出器,你应该从蜘蛛中访问它。这意味着您应该使用蜘蛛将项目写入 CSV 文件,这样在这种情况下您就不需要从 parse_items 方法中产生任何 items——而是实现 process_item那里的方法。所以不需要单独的导出器。

2) exporter 与 spider 在同一个文件中

如果您的导出器与蜘蛛程序位于同一文件中,则必须从 settings.py 文件中指向此导出器 class。假设您的项目位于 new_job 文件夹中,您的蜘蛛的 Python 文件名为 newjob.py。在这种情况下,您可以在 settings.py 中添加以下行:

ITEM_PIPELINES = {'new_job.spiders.newjob.myExporter' : 90,}

顺便说一句,当我复制你的代码时,我遇到了一些需要修复的错误。所以我想知道它是否对你有用。