【问题标题】:How to append dictionary to csv without appending keys如何在不附加键的情况下将字典附加到 csv
【发布时间】:2020-08-04 13:29:26
【问题描述】:

我有一个字典 features = {'feature1' : 'hi', 'feature2': 'second feature', 'feature3': 'third feature'}。我需要将其保存到 csv 文件中。但是这个字典在每次迭代中都会更新,并且一个新的字典会附加到现有的 csv 文件中。我在scrapy中使用它。

class Myspider(SitemapSpider):
    name = 'spidername'
    sitemap_urls = ['https://www.arabam.com/sitemap/otomobil_1.xml']
    sitemap_rules = [
        ('/otomobil/', 'parse'),
        # ('/category/', 'parse_category'),
    ]

    def parse(self,response):


                            yield scrapy.Request(url, callback=self.parse_dir_contents)

    def parse_dir_contents(self,response):
        # print("hi here")
        features = {}
        features["ad_url"] = response.request.url
        #filling feature dictionary
        df = pd.DataFrame.from_dict(features , orient='index')
        df = df.transpose()
        df.to_csv("result.csv",mode = 'a', index = False)

问题是这会将字典和键一起保存到 csv 中。我在这里附上excel表的图片: enter image description here

直观地说,标题应该只在顶部填充一次,而不是每隔一行。我该怎么做?

【问题讨论】:

  • 你可以删除 pandas 并使用 scrapy 默认的 csv 导出器
  • @wishmaster 请为此提供更多背景信息

标签: python pandas csv dictionary scrapy


【解决方案1】:
class Myspider(SitemapSpider):
    name = 'spidername'
    sitemap_urls = ['https://www.arabam.com/sitemap/otomobil_1.xml']
    sitemap_rules = [
        ('/otomobil/', 'parse'),
        # ('/category/', 'parse_category'),
    ]
    custom_settings = {'FEED_FORMAT':'csv','FEED_URI':'FILEname.csv'}

    def parse(self,response):


        yield scrapy.Request(url, callback=self.parse_dir_contents)

    def parse_dir_contents(self,response):
        # print("hi here")
        item = {}
        item["ad_url"] = response.request.url
        yield item

运行它scrapy crawl spidername

【讨论】:

  • AttributeError: 'FeedExporter' 对象没有属性 'slot'
  • 尝试运行它scrapy crawl spidername -o test.csv
  • 它不是一个乱七八糟的项目。我创建了一个 python 文件并在脚本末尾添加了命令来运行它。
  • 问题是我的 csv 是打开的。
猜你喜欢
  • 2017-09-01
  • 2012-09-26
  • 2019-06-29
  • 1970-01-01
  • 2020-04-09
  • 2023-02-24
  • 1970-01-01
  • 2013-11-14
  • 1970-01-01
相关资源
最近更新 更多