爬虫数据存储到数据库——MySQL + MongoDB 实战

📅 2026/7/10 1:55:25 👁️ 阅读次数 📝 编程学习
爬虫数据存储到数据库——MySQL + MongoDB 实战

数据爬下来后,存为 CSV 或 JSON 虽然简单,但查询和更新不方便。当数据量上万条时,建议存入数据库。这篇讲爬虫数据如何写入 MySQL 和 MongoDB。

一、MySQL 存储

1. 建表

CREATETABLEproducts(idBIGINTAUTO_INCREMENTPRIMARYKEY,source_idVARCHAR(100)NOTNULL,titleVARCHAR(200)NOTNULL,priceDECIMAL(10,2),brandVARCHAR(100),crawl_timeDATETIME,UNIQUEKEYuk_source_id(source_id))ENGINE=InnoDBDEFAULTCHARSET=utf8mb4;

2. 写入数据

importpymysqldefsave_to_mysql(items):conn=pymysql.connect(host="localhost",user="root",password="123456",database="spider_db",charset="utf8mb4")cursor=conn.cursor()sql="""INSERT INTO products (source_id, title, price, brand, crawl_time) VALUES (%s, %s, %s, %s, %s) ON DUPLICATE KEY UPDATE price = VALUES(price)"""foriteminitems:cursor.execute(sql,(item["source_id"],item["title"],item["price"],item["brand"],datetime.now()))conn.commit()cursor.close()conn.close()

二、MongoDB 存储

frompymongoimportMongoClient client=MongoClient("localhost",27017)db=client["spider_db"]collection=db["products"]# 插入collection.insert_many(items)# 去重更新(有则更新,无则插入)foriteminitems:collection.update_one({"source_id":item["source_id"]},{"$set":item},upsert=True)

💡 觉得有用的话,点赞 + 关注【张老师技术栈】吧!