2017-08-09 52 views
0

我瀏覽了這個網站,我在谷歌上也做了同樣的工作,但是我沒有發現任何關於導出編碼爲UTF-8的csv文件的數據。Scrapy - 編碼csv文件utf-8

我需要編碼我的文件,因爲我有一些法語字符(如É)。 我使用CsvItemExporter,它通常已經在utf-8中編碼,但它不會給我正確的字符。而不是這些字符,我只有像\ A4ybzkzv一些奇怪的東西,我不知道如何有正確的。

我希望我已經清楚了!謝謝你的幫助...

這裏是我的pipelines.py:

# -*- coding: utf-8 -*- 
from scrapy import signals 
from scrapy.exporters import CsvItemExporter 

# Define your item pipelines here 
# 
# Don't forget to add your pipeline to the ITEM_PIPELINES setting 
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html 

# Define your output file. 
class FnacPipeline(CsvItemExporter): 
    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): 
     f = open('..\\..\\..\\..\\Fnac.csv', 'w').close() 
     file = open('..\\..\\..\\..\\Fnac.csv', 'w') 
     self.files[spider] = file 
     self.exporter = CsvItemExporter(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 

有了這個管道,我有一個錯誤,而不是正確的字符:TypeError: must be str, not bytes當我改變file = open('..\\..\\..\\..\\Fnac.csv', 'w')file = open('..\\..\\..\\..\\Fnac.csv', 'wb'),我沒有更多的錯誤,但不正確的字符...

輸出我有: France métropolitaine

我想要的輸出: France métropolitaine

+2

快問,你爲什麼不內置scrapy出口商使用?你可以簡單地用'-o'標誌導出你的結果:'scrapy crawl myspider -o results.csv'或者你也可以設置[一些設置來做到這一點](https://doc.scrapy.org/en/latest/主題/饋exports.html)。 – Granitosaurus

+0

@Granitosaurus說過,我認爲一些設置或定製是他正在做的確切的事情。:) – Nabin

+0

因爲我有很多項目,有時在同一個項目中有很多蜘蛛,我想通過蜘蛛創建一個csv文件...我通過可執行文件自動運行我的蜘蛛。所以我不想重新寫我的exe文件,每次我想運行一個蜘蛛:) –

回答

2

打開文本文件與Python 3書寫使用UTF-8編碼的正確方法是如下:

fd = open(path, mode='w', encoding='utf-8') 
fd.write("Unicode string") 

但是你CsvItemExporter接縫做的編碼爲你,所以你寫二進制數據到您的文件。所以,最好的辦法是打開文件的二進制格式:

fd = open(path, mode='wb') 
fd.write(b"Binary string") 

結果:「法國MA©tropolitaine」是正確的。問題是你不使用正確的編輯器來讀取你的文件。你當然使用Excel。並且Excel在法文版上默認使用cp1252打開CSV文件。您需要導入文件才能選擇源編碼。注意:Libre Office不會有這個問題。

+1

我剛剛打開我的文件,因爲你告訴我(在Excel中,導入數據...),你是對的...我沒有以正確的方式打開它...謝謝! –

0

所以正確的答案是將其保存爲utf-8並使用excel Import來查看該屬性。

另一方面,您可以直接打開它在Excel中查看它,但默認編碼是cp12523

對我來說,我不能告訴我的客戶使用excel的Import,所以我選擇將編碼更改爲cp1252,因此它無法正確查看。

當您在settings.py中更改配置時,設置爲FEED_EXPORT_ENCODING = 'utf-8'將不會起作用。

我所做的是改變pipelines.pyspider_opened功能,

self.exporter = CsvItemExporter(file, encoding='cp1252')