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

Scrapy爬取数据写入PostgreSQL报错:事务终止问题求助

问题分析与解决方案

核心错误原因

你的PostgreSQL插入语句存在字段数量与传入值数量不匹配的问题:
SQL语句中指定了content, tags, author三个字段,但只传入了item["flat"]一个值,这直接导致第一次插入失败,触发事务中止,后续所有数据库操作都会因事务未回滚而报错psycopg2.errors.InFailedSqlTransaction。

分步修复

1. 修正SQL插入语句

根据你的数据库表结构选择以下两种方案之一:

  • 如果只需要将flat的值存入content字段:
    def process_item(self, item, spider):
        try:
            self.current.execute("""insert into flats(content) values(%s)""", (item["flat"],))
            self.connection.commit()
        except Exception as e:
            self.connection.rollback()
            spider.logger.error(f"插入失败: {str(e)}")
            raise
        return item
    
  • 如果tags和author字段必须赋值(允许为空的话):
    def process_item(self, item, spider):
        try:
            self.current.execute("""insert into flats(content, tags, author) values(%s, %s, %s)""", 
                                (item["flat"], None, None))
            self.connection.commit()
        except Exception as e:
            self.connection.rollback()
            spider.logger.error(f"插入失败: {str(e)}")
            raise
        return item
    

2. 添加事务异常处理

必须在异常发生时回滚事务,否则后续所有数据库操作都会被阻塞。上面的代码已经包含了try-except块,捕获异常后执行self.connection.rollback(),确保事务状态重置。

3. 修正Parse函数的潜在问题

当前Parse函数中FlatItem只初始化一次,循环中反复赋值yield可能导致Item对象被复用(虽然Scrapy会处理,但不符合规范),建议每次循环创建新的Item实例:

def parse(self, response):
    data = json.loads(response.body)
    for item in data["_embedded"]["estates"]:
        flat = FlatItem()  # 移到循环内,每次创建新实例
        flat['flat'] = item['price']
        yield flat

验证步骤

  1. 确认数据库表flats的字段类型与传入值匹配(比如content是否能存储数字类型的价格)
  2. 运行爬虫,观察是否还有事务相关报错

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 22:10:48