使用Scrapy爬虫通过Item Pipeline存入MySQL数据库失败求助
核心问题定位
从你提供的运行日志统计项可以看到scraped 0 items,说明你的爬虫在运行全程没有生成并抛出任何有效Item,Pipeline的process_item方法从未被触发,这是你看不到打印内容、数据也没有入库的核心原因。
分步排查方案
第一步:确认爬虫是否正确生成并抛出Item(最高优先级)
- 检查spiders目录下的爬虫脚本,确认页面解析逻辑的xpath/css选择器是否正确,能否正常从返回的页面中提取到目标字段
- 检查解析到字段后,是否正确封装为
MonitorItem对象,并用yield关键字抛出(不要用return,return不会把Item交给Pipeline处理) - 可以临时把settings里的
LOG_LEVEL改成DEBUG,或者直接在parse方法里加打印,确认是否走到了yield Item的逻辑分支
第二步:修复Pipeline本身的逻辑缺陷
你的现有Pipeline代码存在两处明显不符合规范的问题:
process_item方法只有捕获到数据库异常时才返回item,正常执行完成后没有返回值,不符合Scrapy Pipeline的要求- 捕获到数据库异常后没有回滚事务,会导致后续的数据库操作异常
- 额外注意:你代码中__init__方法读取了config.ini配置,但实际数据库连接参数是硬编码的,确认硬编码的数据库地址、账号、密码、库名是否和实际环境一致
修正后的Pipeline参考代码:
from configparser import ConfigParser import os, pathlib import pymysql class MonitorPipeline(object): def __init__(self): configs = ConfigParser() path = pathlib.Path(os.path.realpath(__file__)) configs.read(path.parent.parent/'config.ini') self.mysql_connection = pymysql.connect( host='localhost', user='technophile', password='tech@nophile343', db='storage', charset='utf8mb4' # 新增字符集设置,避免中文乱码 ) self.cursor = self.mysql_connection.cursor() def process_item(self, item, spider): try: self.cursor.execute("""insert into complete_info(id, company_id, exchange_id, doc_name, doc_link, publication_date, update_timestamp, session_id, doctype_code, language_code) VALUES (%s,%s,%s,%s,%s,%s, %s,%s,%s,%s)""", (item['id'], item['company_id'], item['exchange_id'], item['doc_name'], item['doc_link'], item['publication_date'], item['update_timestamp'], item['session_id'], item['doctype_code'], item['language_code'])) self.mysql_connection.commit() print('It is saved!!') except pymysql.Error as e: print("Error %d: %s" % (e.args[0], e.args[1])) self.mysql_connection.rollback() # 新增异常回滚 return item # 必须返回item def close_spider(self, spider): self.cursor.close() self.mysql_connection.close()
第三步:排查数据库侧的问题
可以单独测试数据库写入逻辑是否正常:
- 用代码中的账号密码手动登录MySQL,确认是否有
storage库的读写权限,complete_info表是否存在 - 确认表结构和Item字段完全对应:字段名是否一致、字段类型/长度是否匹配、有没有非空字段你没有传值、主键id是否重复
- 可以写一个简单的测试脚本,手动构造一个MonitorItem对象,调用process_item方法,看是否能正常写入数据库,排除数据库侧的问题
内容的提问来源于stack exchange,提问作者technophile_3
相关产品推荐
相关产品推荐

