6
votes

here is the spider:

import scrapy
from danmurphys.items import DanmurphysItem

class MySpider(scrapy.Spider):
    name = 'danmurphys'
    allowed_domains = ['danmurphys.com.au']
    start_urls = ['https://www.danmurphys.com.au/dm/navigation/navigation_results_gallery.jsp?params=fh_location%3D%2F%2Fcatalog01%2Fen_AU%2Fcategories%3C%7Bcatalog01_2534374302084767_2534374302027742%7D%26fh_view_size%3D120%26fh_sort%3D-sales_value_30_days%26fh_modification%3D&resetnav=false&storeExclusivePage=false']


    def parse(self, response):        
        urls = response.xpath('//h2/a/@href').extract()
        for url in urls:            
            request = scrapy.Request(url , callback=self.parse_page)      
            yield request

    def parse_page(self , response):
        item = DanmurphysItem()
        item['brand'] = response.xpath('//span[@itemprop="brand"]/text()').extract_first().strip()
        item['name'] = response.xpath('//span[@itemprop="name"]/text()').extract_first().strip()
        item['url'] = response.url     
        return item

and here is the items :

import scrapy
class DanmurphysItem(scrapy.Item):  
    brand = scrapy.Field()
    name = scrapy.Field()
    url = scrapy.Field()

when I run the spider with this command :

scrapy crawl danmurphys -o output.csv

the output is like this : enter image description here

5
where is the csv file written? in your software or in scrapy? Are you working on windows? - Jean-François Fabre♦
I'm working on windows , and I type the crawl command in cmd , the file is written in the project folder . - Ibrahim
@Ibrahim, can I ask you to open an issue on scrapy on GitHub? That would be great. - paul trmbrth
OK , that's fine , I'm going to do that . - Ibrahim

5 Answers

9
votes

To fix this in Scrapy 1.3, you can patch it by adding newline='' as parameter to io.TextIOWrapper in the __init__ method of the CsvItemExporter class in scrapy.exporters.

2
votes

This output shows the typical symptom of csv file handle opened using "w" mode on windows (to fix Python 3 compatibility maybe) but omitting newline.

While this has no effect on Linux/Unix based systems, on Windows, 2 carriage return chars are issued, inserting a fake blank line after every data line.

with open("output.csv","w") as f:
     cr = csv.writer(f)

correct way of doing it (python 3):

with open("output.csv","w",newline='') as f:  # python 3
     cr = csv.writer(f)

(in python 2, setting "wb" as open mode fixes it)

If the file is created by a program you cannot or do not want to modify, you can always post-process the file as follows:

with open("output.csv","rb") as f:
   with open("output_fix.csv","w") as f2:
       f2.write(f.read().decode().replace("\r","")) # python 3
       f2.write(f.read().replace("\r","")) # python 2
1
votes

Scrapy 1.5.0 && Python 3.6.5 :: Anaconda, Inc.

I manage to solve this problem by following these steps :


Folder structure

C:.
|   scrapy.cfg
|
\---my_scraper
    |   exporters.py
    |   items.py
    |   middlewares.py
    |   pipelines.py
    |   settings.py
    |   __init__.py
    |
    +---spiders
    |   |   my_spider.py
    |   |   __init__.py
    |

exporters.py

# -*- coding: utf-8 -*-
import csv
import io
import os
import six

from scrapy.conf import settings
from scrapy.exporters import CsvItemExporter

from scrapy.extensions.feedexport import IFeedStorage
from w3lib.url import file_uri_to_path
from zope.interface import implementer

@implementer(IFeedStorage)
class FixedFileFeedStorage(object):

    def __init__(self, uri):
        self.path = file_uri_to_path(uri)

    def open(self, spider):
        dirname = os.path.dirname(self.path)
        if dirname and not os.path.exists(dirname):
            os.makedirs(dirname)
        return open(self.path, 'ab')

    def store(self, file):
        file.close()



class MyCsvItemExporter(CsvItemExporter):

    def __init__(self, file, include_headers_line=True, join_multivalued=',', **kwargs):

        # Custom delimiter
        delimiter = settings.get('CSV_DELIMITER', ';')
        kwargs['delimiter'] = delimiter

        super(MyCsvItemExporter, self).__init__(file, include_headers_line, join_multivalued, **kwargs)

        self._configure(kwargs, dont_fail=True)
        self.stream.close()
        storage = FixedFileFeedStorage(file.name)
        file = storage.open(file.name)
        self.stream = io.TextIOWrapper(
            file,
            line_buffering=False,
            write_through=True,
            encoding=self.encoding,
            newline="",
        ) if six.PY3 else file
        self.csv_writer = csv.writer(self.stream, **kwargs)

settings.py

# ...

FEED_EXPORT_ENCODING = 'utf-8'

FEED_EXPORTERS = {
    'csv': 'my_scraper.exporters.MyCsvItemExporter',
}

CSV_DELIMITER = ';'

I hope this was helpful for you

0
votes

Thanks everybody especially (Jean-François)

the problem was that I've installed another scrapy version 1.1.0 installed from conda for python 3.5 once I added python 2.7 in system path ,the original scrapy 1.1.2 returned to work as default . and everything works just fine .

0
votes

I solved it via the pipelines.py file:

i suspect not ideal but I have found a work around to this problem. In the pipelines.py file I have added more code that essentially reads the csv file with the blank lines to a list, and so removes the blank lines and then writes that cleaned list to a new file.

the code I added is:

with open('%s_items.csv' % spider.name, 'r') as f:
  reader = csv.reader(f)
  original_list = list(reader)
  cleaned_list = list(filter(None,original_list))

with open('%s_items_cleaned.csv' % spider.name, 'w', newline='') as output_file:
    wr = csv.writer(output_file, dialect='excel')
    for data in cleaned_list:
      wr.writerow(data)

Therefore, details of the entire pipelines.py file is Scrapy python csv output has blank lines between each row