如何将python爬出来的数据保存_python爬虫第7篇——爬取的数据如何存档
时间: 2024-02-13 13:06:03 浏览: 196
可以使用以下几种方式将Python爬虫爬取到的数据保存起来:
1. 保存为文本文件:可以使用Python内置的open函数将数据保存为txt文件。
```python
with open('data.txt', 'w', encoding='utf-8') as f:
f.write(data)
```
2. 保存为CSV文件:如果数据是表格形式的,可以使用Python内置的csv模块将数据保存为CSV文件。
```python
import csv
with open('data.csv', 'w', newline='', encoding='utf-8') as f:
writer = csv.writer(f)
writer.writerow(['title', 'author', 'date', 'content'])
writer.writerows(data)
```
3. 保存为JSON文件:可以使用Python内置的json库将数据保存为JSON格式的文件。
```python
import json
with open('data.json', 'w', encoding='utf-8') as f:
json.dump(data, f, ensure_ascii=False, indent=4)
```
4. 保存到数据库:如果需要对数据进行查询和分析,可以将数据保存到数据库中,比如MySQL、SQLite、MongoDB等。
```python
import pymysql
conn = pymysql.connect(host='localhost', user='root', password='password', db='test', charset='utf8')
cursor = conn.cursor()
sql = "INSERT INTO `news`(`title`, `author`, `date`, `content`) VALUES (%s, %s, %s, %s)"
for item in data:
cursor.execute(sql, (item['title'], item['author'], item['date'], item['content']))
conn.commit()
cursor.close()
conn.close()
```
以上是几种常见的数据保存方式,具体选择哪种方式取决于实际需求。
阅读全文
相关推荐















