【发布时间】: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