2016-04-27 2 views
0

Привет я новичок в Python/Scrapy мире, мне нужно экспортировать мой список продуктов Csv как этот Exemple: what i want , но я получаю это: what i gotвыход питона в CSV регулярные

// /// паук: /////

import scrapy 
import csv 
from escrap.items import EscrapItem 

class EscrapSpider(scrapy.Spider): 
    name = "tunisianet" 
    allowed_domains = ["tunisianet.com.tn"] 
    start_urls = [ 
     "http://www.tunisianet.com.tn/385-logiciels-informatique-tunisie/" 
    ] 

    def parse(self, response): 
     for sel in response.xpath('//*[contains(@class, "ajax_block_product")]'): 
      item = EscrapItem() 
      item['revendeur'] = '\n'.join(sel.xpath('//*[contains(@class, "center_block")]/h2/a/@href').re('tunisianet')) 
      item['produit'] = '\n'.join(sel.xpath('//*[contains(@class, "center_block")]/h2/a/text()').extract()) 
      item['lien'] = '\n'.join(sel.xpath('//*[contains(@class, "center_block")]/h2/a/@href').extract()) 
      item['description'] = '\n'.join(sel.xpath('//*[contains(@class, "product_desc")]/a/text()').extract()) 
      item['prix'] = '\n'.join(sel.xpath('//*[contains(@class, "price")]/text()').extract()) 
     data = [item['revendeur'], item['produit'], item['lien'], item['description'], item['prix']] 
     out = open('out.csv', 'w') 
     for row in data: 
      for column in row: 
       out.write(column.encode('utf-8')) 
     return data 

///// пунктов: // ///

import scrapy 

class EscrapItem(scrapy.Item): 
    revendeur = scrapy.Field() 
    produit = scrapy.Field() 
    lien = scrapy.Field() 
    description = scrapy.Field() 
    prix = scrapy.Field() 

///// трубопроводы: /////

class EscrapPipeline(object): 

    # put all words in lowercase 
    words_to_filter = ['politics', 'religion'] 
    def process_item(self, item, spider): 
     for word in self.words_to_filter: 
      if word in  unicode([item['revendeur'],item['produit'],item['lien'],item['description'],item ['prix']]).lower(): 
       raise DropItem("Contains forbidden word: %s" % word) 
     else: 
      return item 

///// мои настройки: /////

BOT_NAME = 'escrap' 

SPIDER_MODULES = ['escrap.spiders'] 
NEWSPIDER_MODULE = 'escrap.spiders' 
ITEM_PIPELINES = {'escrap.pipelines.EscrapPipeline': 1} 
FEED_EXPORTERS = { 
    'csv': 'escrap.escrap_csv_item_exporter.EscrapCsvItemExporter', 
} 
FIELDS_TO_EXPORT = [ 
    'revendeur', 
    'produit', 
    'lien', 
    'description', 
    'prix' 
] 
+0

Что представляют собой элементы в 'data'? Из результата, который вы получаете, похоже, что данные, которые у вас есть в 'data', могут быть не такими, какие вы ожидаете. –

+0

Элементы в данных представляют собой продукты (имя продавца, название продукта, описание ,,)) 'data = [item ['revendeur'], item ['produit'], item ['lien'], item ['description '], item [' prix ']] ' –

ответ

0

Возможно, вы должны установить ячейку, в которую вы хотите записать y ou данные. Что-то вроде:

worksheet.write('A1','thing you want to write') 

Или это может быть по умолчанию для записи контента в «A»

1

Вам не нужно, чтобы создать CSV-файл самостоятельно при анализе элементов, SCRAPY может экспортировать по умолчанию в файл CSV ,

так изменить метод parse к:

def parse(self, response): 
    for sel in response.xpath('//*[contains(@class, "ajax_block_product")]'): 
     item = EscrapItem() 
     item['revendeur'] = '\n'.join(sel.xpath('//*[contains(@class, "center_block")]/h2/a/@href').re('tunisianet')) 
     item['produit'] = '\n'.join(sel.xpath('//*[contains(@class, "center_block")]/h2/a/text()').extract()) 
     item['lien'] = '\n'.join(sel.xpath('//*[contains(@class, "center_block")]/h2/a/@href').extract()) 
     item['description'] = '\n'.join(sel.xpath('//*[contains(@class, "product_desc")]/a/text()').extract()) 
     item['prix'] = '\n'.join(sel.xpath('//*[contains(@class, "price")]/text()').extract()) 
     yield item 

позже при вызове Scrapy вы можете назвать его:

scrapy crawl myspider -o output.csv 

Теперь у вас есть все элементы, экспортируемые в файл CSV.

Если вы все еще хотите управлять им на своем собственном трубопроводе, отметьте здесь create your own exporter. Он хотел бы это:

from scrapy import signals 
from scrapy.exporters import CsvItemExporter 

class CSVExportPipeline(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.csv' % spider.name, 'w+b') 
     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 

Чтобы создать свой собственный трубопровод убедитесь read этого полностью.

+0

Я бы хотел экспортировать их без -o output.csv, и проблема в том, что у меня нет идеи об экспорте товаров:/ –

+0

проверить обновленный ответ – eLRuLL

+0

помог для экспорта ваших данных? – eLRuLL

0

это экспорт, но не с формой, которую я хочу, мне нужна форма, подобная этой: http://i.imgur.com/r8LaVem.png, но я получил этот http://i.imgur.com/8IVnlui.png. вот мой последний класс: def parse(self, response): item = TfawItem() data= [] items = [] out = open('out.csv', 'a') x = response.xpath('//*[contains(@class, "ajax_block_product")]') for i in range(0, len(x)): item['revendeur'] = response.xpath('//*[contains(@class, "center_block")]/h2/a/@href').re('tunisianet')[i] item['produit'] = response.xpath('//*[contains(@class, "center_block")]/h2/a/text()').extract()[i] item['url'] = response.xpath('//*[contains(@class, "center_block")]/h2/a/@href').extract()[i] item['description'] = response.xpath('//*[contains(@class, "product_desc")]/a/text()').extract()[i] item['prix'] = response.xpath('//*[contains(@class, "price")]/text()').extract()[i] data = item['revendeur'], item['produit'], item['url'], item['description'], item['prix'] out.write(str(data)) out.write('\n')

Смежные вопросы