Python爬虫获取名言数据插入MySQL时出现参数未使用错误的问题排查求助
解决MySQL插入名言数据时的"Not all parameters were used"错误
让我们一步步拆解你代码里的问题,以及对应的修复方案:
核心错误点
- 占位符大小写错误:MySQL Connector for Python要求用小写的
%s作为参数占位符,但你写的是大写的%S,这会导致驱动无法正确识别参数位置。 - 参数结构与插入方法不匹配:你的
quote是纯字符串列表,但SQL语句需要id和Quotes两个参数,你却没有为每条名言提供对应的id值;另外批量插入要使用executemany()而非execute()——execute()仅能处理单条数据,executemany()才是批量插入的正确方法。 - id字段冗余处理:如果你的
quoteslist表中id是自增主键(这是最常见的设计),完全不需要手动传入id值,数据库会自动帮你生成唯一的id。
修正后的完整代码
import mysql.connector from bs4 import BeautifulSoup import requests URL = "https://parade.com/937586/parade/life-quotes/" web_page = requests.get(URL) soup = BeautifulSoup(web_page.text, "html.parser") # 将每条名言包装成元组,适配executemany的参数格式 quotes = [(x.get_text(strip=True, separator=" "),) for x in soup.select('span[data-parade-type="promoarea"] .figure_block ~ p')] # 数据库连接逻辑 db = mysql.connector.Connect( host="127.0.0.1", user="root", password="Demon@", database="my_quotes", charset="utf8mb4" ) mycursor = db.cursor() # 因为id是自增主键,SQL语句只需指定Quotes字段 sql = "INSERT INTO quoteslist (Quotes) VALUES (%s)" # 用executemany批量插入多条数据 mycursor.executemany(sql, quotes) db.commit() print(f"成功插入 {mycursor.rowcount} 条名言数据") db.close()
额外补充说明
如果你的id不是自增字段,需要手动生成id的话,可以用enumerate为每条名言分配序号:
# 从1开始生成连续id,包装成(id, 名言)的元组格式 quotes = [(i+1, x.get_text(strip=True, separator=" ")) for i, x in enumerate(soup.select('span[data-parade-type="promoarea"] .figure_block ~ p'))] # 对应的SQL语句需要同时指定id和Quotes字段 sql = "INSERT INTO quoteslist (id, Quotes) VALUES (%s, %s)"
另外建议给数据库操作加上try-except异常捕获,避免因网络波动或数据库连接异常导致程序直接崩溃。
内容的提问来源于stack exchange,提问作者user16622907
相关产品推荐
相关产品推荐

