简体   繁体   中英

Python - How do I format scrapy data in a csv file?

I am new to python and web scraping and I tried storing the scrapy data to a csv file however the output is not satisfactory.

Current csv output:

Title             Image
Audi,Benz,BMW     Image1,Image2,Image3

how i would like to view it in a csv file:

Title     Image
Audi      Image1
Benz      Image2
BMW       Image3

this is what is type in the terminal to run it:

scrapy crawl testscraper -t csv -o test.csv

Here's the spider.py:

class TestSpiderSpider(scrapy.Spider):
name = 'testscraper'
page_number = 2
start_urls = ['https://jamaicaclassifiedonline.com/auto/cars/']

    def parse(self, response):
    items = scrapeItem()

    product_title = response.css('.jco-card-title::text').extract()
    product_imagelink = response.css('.card-image img::attr(data-src)').getall()

    items['product_title'] = product_title
    items['product_imagelink'] = product_imagelink
    items.append('items')

    yield items

He's the code for items.py:

class scrapeItem(scrapy.Item):
product_title = scrapy.Field()
product_imagelink = scrapy.Field()

pass

You can select every div element that contains a car and then iterate over those elements, yielding them one by one.

def parse(self, response):

        for car in response.css('.col.l3.s12.m6'):
            item = scrapeItem()

            product_title = car.css('.jco-card-title::text').get()
            product_imagelink = car.css('.card-image img::attr(data-src)').get()

            # Some of the elements don't contain a title or a image_link, like ads for example.
            if product_title and product_imagelink:

                item['product_title'] = product_title.strip().replace('\n', '')
                item['product_imagelink'] = product_imagelink

                yield item

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM