Python爬取數(shù)據(jù)存入MySQL的方法有以下幾種:
import MySQLdb
# 建立數(shù)據(jù)庫連接
db = MySQLdb.connect(host="localhost", user="root", passwd="password", db="database")
# 創(chuàng)建游標(biāo)對象
cursor = db.cursor()
# 執(zhí)行SQL語句
sql = "INSERT INTO table (column1, column2) VALUES ('value1', 'value2')"
cursor.execute(sql)
# 提交數(shù)據(jù)庫事務(wù)
db.commit()
# 關(guān)閉游標(biāo)和數(shù)據(jù)庫連接
cursor.close()
db.close()
import pymysql
# 建立數(shù)據(jù)庫連接
db = pymysql.connect(host="localhost", user="root", passwd="password", db="database")
# 創(chuàng)建游標(biāo)對象
cursor = db.cursor()
# 執(zhí)行SQL語句
sql = "INSERT INTO table (column1, column2) VALUES ('value1', 'value2')"
cursor.execute(sql)
# 提交數(shù)據(jù)庫事務(wù)
db.commit()
# 關(guān)閉游標(biāo)和數(shù)據(jù)庫連接
cursor.close()
db.close()
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from your_module import Base
# 建立數(shù)據(jù)庫連接
engine = create_engine('mysql://user:password@localhost/database')
Base.metadata.bind = engine
# 創(chuàng)建數(shù)據(jù)庫會話對象
DBSession = sessionmaker(bind=engine)
session = DBSession()
# 插入數(shù)據(jù)
new_data = YourTable(column1='value1', column2='value2')
session.add(new_data)
session.commit()
# 關(guān)閉會話
session.close()
以上是三種常用的Python爬取數(shù)據(jù)存入MySQL的方法,可以根據(jù)自己的需求選擇適合的方法進行使用。