scrapy无法存入数据

当整个scrapy爬取框架搭建好后,items,pipeline都设置好了,却发现通过Pipeline无法存入文件,这时候就需要设置settings.py了

  • 在scrapy中settings中pipeline的开关是默认关闭的,需要将其注释去掉,之后就可以发挥scrapy的大刀啦。
# Configure item pipelines
# See http://scrapy.readthedocs.org/en/latest/topics/item-pipeline.html
ITEM_PIPELINES = {'tutorial.pipelines.TutorialPipeline': 300,
}
### 配置项设置 为了使Scrapy能够将数据保存到MySQL数据库中,需要修改`settings.py`文件中的配置来激活自定义的Pipeline,并设定必要的数据库连接参数。具体来说: - 设置`ITEM_PIPELINES`字典以启用特定项目的管道类[^2]。 ```python ITEM_PIPELINES = { 'your_project_name.pipelines.YourProjectNamePipeline': 300, } ``` - 定义用于访问MySQL数据库的相关环境变量,这些信息通常也放置于同一文件内以便管理。 ```python MYSQL_CONFIG = { "HOST": "localhost", "PORT": 3306, "USER": "root", "PASSWORD": "your_password", "DATABASE": "your_database" } ``` 以上操作确保了当Spider处理完网页内容并将提取出来的Item传递给Pipeline时,后者知道要将其入哪个数据库以及如何建立这种联系。 ### 编Pipeline 接下来创建一个新的Python模块作为Pipeline的一部分,负责接收来自Spiders的数据对象并执行实际的持久化逻辑。以下是实现这一功能的一个简单例子[^1]。 #### 创建 `pipelines.py` 在项目根目录下编辑或新建名为`pipelines.py`的文件,加入如下代码片段: ```python import pymysql class YourProjectNamePipeline(object): def __init__(self): self.conn = None self.cursor = None @classmethod def from_crawler(cls, crawler): pipeline = cls() host = crawler.settings.get('MYSQL_CONFIG')['HOST'] port = crawler.settings.get('MYSQL_CONFIG')['PORT'] user = crawler.settings.get('MYSQL_CONFIG')['USER'] password = crawler.settings.get('MYSQL_CONFIG')['PASSWORD'] database = crawler.settings.get('MYSQL_CONFIG')['DATABASE'] pipeline.connect_db(host, port, user, password, database) return pipeline def connect_db(self, host, port, user, password, db): """Connect to the MySQL database.""" try: self.conn = pymysql.connect( host=host, port=int(port), user=user, passwd=password, db=db, charset='utf8mb4' ) self.cursor = self.conn.cursor() except Exception as e: raise ConnectionError(f"Failed connecting to MySQL server: {e}") def process_item(self, item, spider): sql = """ INSERT INTO articles(title, author, publish_date) VALUES (%s,%s,%s); """ values = ( item['title'], item['author'], item['publish_date'] ) try: self.cursor.execute(sql, values) self.conn.commit() except Exception as error: print(error) self.conn.rollback() # Rollback in case there is any error finally: return item def close_spider(self, spider): if hasattr(self, 'cursor') and self.cursor: self.cursor.close() if hasattr(self, 'conn') and self.conn: self.conn.close() ``` 这段脚本实现了几个重要的方法:初始化数据库连接(`__init__()`);从Crawler实例获取设置并通过它们打开数据库链接(`from_crawler()`); 插入新记录(`process_item()`) 和关闭资源 (`close_spider()`)。 通过上述步骤,已经完成了基本的功能需求——即让Scrapy抓取的内容被妥善地存储到了指定的MySQL表结构之中。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值