You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

无法导入网络爬取数据至MySQL数据库,遇类型转换错误求助

解决Python列表类型无法存入MySQL的错误

错误原因

报错_mysql_connector.MySQLInterfaceError: Python type list cannot be converted的核心问题是:你传入MySQL的字段值为列表类型,但数据库表定义的title(text)、link(text)、price(float)均为单个值类型,无法直接转换列表数据。

同时你的代码存在两个潜在问题:

  • 爬虫返回的item字段(如title/link/price)是列表(通常是爬虫使用extract()而非extract_first(),或选择器返回了多结果导致)。
  • process_item方法每次提交后就关闭数据库连接,后续处理其他item时会因连接已关闭报错。

修正方案

步骤1:修正爬虫字段获取逻辑

确保爬虫返回的每个字段是单个值,例如:

  • 将response.xpath('//h1/text()').extract()改为response.xpath('//h1/text()').extract_first()
  • 或通过[0]取列表第一个元素(需处理空列表场景)

步骤2:修正Pipeline代码

import mysql.connector

class WatsonPipeline:
    def __init__(self):
        self.con = mysql.connector.connect(
            host='127.0.0.1',
            user='root',
            passwd='5779ra',
            database='watson')
        self.cur = self.con.cursor()
        # 新增IF NOT EXISTS,避免重复执行时触发表已存在的报错
        self.cur.execute("""
        create table if not exists dahyun_table(
        title text,
        link text,
        price float
        )""")

    def process_item(self, item, spider):
        # 处理列表类型字段,转换为单个值
        title = item['title'][0].strip() if isinstance(item['title'], list) else str(item['title']).strip()
        link = item['link'][0].strip() if isinstance(item['link'], list) else str(item['link']).strip()
        # 确保price转换为float类型
        price = float(item['price'][0]) if isinstance(item['price'], list) else float(item['price'])

        self.cur.execute("""
        insert into dahyun_table (title,link,price) values (%s,%s,%s)""",(
            title,
            link,
            price
        ))
        self.con.commit()
        return item

    def close_spider(self, spider):
        # 爬虫结束时统一关闭游标和连接,避免多次创建/关闭连接
        self.cur.close()
        self.con.close()

关键说明

  • if not exists:避免爬虫重启时因重复创建表报错。
  • 字段类型转换:通过判断是否为列表,提取第一个元素并做格式处理,确保符合数据库字段要求。
  • close_spider方法:爬虫结束时才关闭连接,避免处理多item时连接已失效的问题。

内容的提问来源于stack exchange,提问作者Aristotle Aletheia

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 15:35:41