Python爬取数据存入MySQL的方法有以下几种:
使用Python的MySQLdb模块:MySQLdb是Python与MySQL数据库交互的接口模块,可以通过安装MySQLdb模块并导入使用,通过执行SQL语句将爬取到的数据插入MySQL数据库中。import MySQLdb# 建立数据库连接db = MySQLdb.connect(host="localhost", user="root", passwd="password", db="database")# 创建游标对象cursor = db.cursor()# 执行SQL语句sql = "INSERT INTO table (column1, column2) VALUES ('value1', 'value2')"cursor.execute(sql)# 提交数据库事务db.commit()# 关闭游标和数据库连接cursor.close()db.close()使用Python的pymysql模块:pymysql是一个纯Python编写的MySQL数据库驱动,可以通过安装pymysql模块并导入使用,通过执行SQL语句将爬取到的数据插入MySQL数据库中。import pymysql# 建立数据库连接db = pymysql.connect(host="localhost", user="root", passwd="password", db="database")# 创建游标对象cursor = db.cursor()# 执行SQL语句sql = "INSERT INTO table (column1, column2) VALUES ('value1', 'value2')"cursor.execute(sql)# 提交数据库事务db.commit()# 关闭游标和数据库连接cursor.close()db.close()使用Python的SQLAlchemy模块:SQLAlchemy是Python中的一个数据库工具包,可以通过安装SQLAlchemy模块并导入使用,通过建立数据库连接、创建数据库会话对象并插入数据来将爬取到的数据存入MySQL数据库。from sqlalchemy import create_enginefrom sqlalchemy.orm import sessionmakerfrom your_module import Base# 建立数据库连接engine = create_engine('mysql://user:password@localhost/database')Base.metadata.bind = engine# 创建数据库会话对象DBSession = sessionmaker(bind=engine)session = DBSession()# 插入数据new_data = YourTable(column1='value1', column2='value2')session.add(new_data)session.commit()# 关闭会话session.close()以上是三种常用的Python爬取数据存入MySQL的方法,可以根据自己的需求选择适合的方法进行使用。