25.2.11(爬虫学习6)
六、保存数据
当我们提取到需要的信息后,通常需要将数据保存起来,常见的保存方式有保存到CSV文件或数据库.
1. 保存到CSV文件
import csv # 保存数据到CSV文件 with open('data.csv', 'w', newline='', encoding='utf-8') as file: writer = csv.writer(file) writer.writerow(['标题', '链接']) # 写入表头 for link in links: writer.writerow([link.text, link.get('href')])
2. 保存到数据库
可以使用 SQLite 或其他数据库,将数据保存到数据库中.
import sqlite3 # 连接数据库(如果不存在会自动创建) conn = sqlite3.connect('data.db') cursor = conn.cursor() # 创建表 cursor.execute('CREATE TABLE IF NOT EXISTS links (title TEXT, href TEXT)') # 插入数据 for link in links: cursor.execute('INSERT INTO links (title, href) VALUES (?, ?)', (link.text, link.get('href'))) # 提交事务并关闭连接 conn.commit() conn.close()

浙公网安备 33010602011771号