首页 > 解决方案 > Scrapy:抓取到 CSV 文件 - 获取无组织的 CSV 文件

问题描述

我正在蜘蛛中实现以下代码,用于从电子商务网站上刮鞋。

 import scrapy

 class HugobossSpider(scrapy.Spider):
 name = 'hugoboss'
 allowed_domains = ['hugoboss.com/de/boss-herren-neuheiten-schuhe/']
 start_urls = ['http://hugoboss.com/de/boss-herren-neuheiten-schuhe//']

     def parse(self, response):
     #Extracting the content using css selectors
     url = response.xpath('//div/@data-mouseoverimage').extract()  
     product_title = response.xpath('//*[@class="product-tile__productInfoWrapper product-tile__productInfoWrapper--is-small font__subline"]/text()').extract()
     price = response.css('.product-tile__offer .price-sales::t Zext').getall()  
     #Give the extracted content row wise
     for item in zip(url,product_title,price):
         #create a dictionary to store the scraped info
         scraped_info = {
             'url' : item[0],
             'product_title' : item[1],
             'price' : item[2]
         }

并且shell像这样正常返回输出

https://imgur.com/a/HJ1U78M

但是,输出的 CSV 文件看起来像这样杂乱无章,

https://imgur.com/a/9qpnWeE

我不明白问题出在哪里。

标签: pythonweb-scrapingscrapy

解决方案


从外观上看,你的爬虫已经收集了一堆换行符 ( \n) 以及产品名称。

它似乎也拿起了这个词von,我认为这也不是必需的。

我的建议是做一些字符串操作来摆脱它们: product_title.replace("\n", '').replace("von", "")

最好使用它的原因.replace(x,y)是因为.strip()/.lstrip()/.rstrip()会删除字符串中的匹配字符,并可能从您的产品名称中删除必要的字符。

希望这可以帮助


推荐阅读