scrapy爬取数据保存csv
时间: 2023-09-09 19:09:52 浏览: 60
要在Scrapy中将数据保存为CSV文件,可以按照以下步骤操作:
1. 在items.py中定义要保存的数据字段,例如:
```python
import scrapy
class MyItem(scrapy.Item):
name = scrapy.Field()
price = scrapy.Field()
```
2. 在settings.py中设置输出格式为CSV,例如:
```python
FEED_FORMAT = 'csv'
FEED_URI = 'output.csv'
```
3. 在pipelines.py中编写数据管道,将数据保存为CSV文件,例如:
```python
import csv
class MyPipeline(object):
def __init__(self):
self.file = open('output.csv', 'wb')
self.writer = csv.writer(self.file)
def process_item(self, item, spider):
row = [item['name'], item['price']]
self.writer.writerow(row)
return item
def spider_closed(self, spider):
self.file.close()
```
4. 在settings.py中启用数据管道,例如:
```python
ITEM_PIPELINES = {
'myproject.pipelines.MyPipeline': 300,
}
```
这样,当爬虫运行时,数据就会被存储在output.csv文件中。