通过自定义pipeline保存数据到mysql

首先安装mysqlclient包,推荐使用豆瓣源安装,速度不仅快,还不容易出错。

pip install -i https://pypi.douban.com/simple/ mysqlclient

# -*- coding: utf-8 -*-

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html
import codecs
import json
import MySQLdb
import MySQLdb.cursors



from scrapy.pipelines.images import ImagesPipeline
from scrapy.exporters import JsonItemExporter


class ArticlespiderPipeline(object):
    def process_item(self, item, spider):
        return item


class JsonWithEncodingPipeline(object):
    #自定义json文件的导出
    def __init__(self):
        self.file = codecs.open('article.json', 'w', encoding="utf-8")

    def process_item(self, item, spider):
        lines = json.dumps(dict(item), ensure_ascii=False) + "\n"#确保中文显示正常
        self.file.write(lines)
        return item

    def spider_closed(self, spider):
        self.file.close()


class JsonExporterPipeline(object):
    #调用scrapy提供的json export 导出json文件
    def __init__(self):
        self.file = open('articleexport.json', 'wb')
        self.exporter = JsonItemExporter(self.file, encoding = "utf-8", ensure_ascii=False)
        self.exporter.start_exporting()

    def process_item(self, item, spider):
        lines = json.dumps(dict(item), ensure_ascii=False) + "\n"#确保中文显示正常
        self.exporter.export_item(item)
        return item

    def close_spider(self,spider):
        self.exporter.finish_exporting()


class MysqlPipeline(object):
    def __init__(self):
        self.conn = MySQLdb.connect('localhost', 'root', '1234', 'jobbole', charset = 'utf8', use_unicode = True)
        self.cursor = self.conn.cursor()

    def process_item(self, item, spider):
        insert_sql = """
            insert into jobbole_article(title, create_date, url, fav_nums)
            VALUES (%s, %s, %s, %s)
        """
        self.cursor.execute(insert_sql, (item["title"], item["create_date"], item["url"], item["fav_nums"]))
        self.conn.commit()


class ArticleImagePipeline(ImagesPipeline):
    def item_completed(self,results,item,info):
        for ok,value in results:
            image_file_path = value["path"]
        item["front_image_path"] = image_file_path
        return item



我遇到的几个问题是:①

    def __init__(self):
        self.conn = MySQLdb.connect('localhost', 'root', '1234', 'jobbole', charset = 'utf8', use_unicode = True)
        self.cursor = self.conn.cursor()

在这个函数中我把主机名弄成Jobbole,即我的连接名称,但这是错的,应该改为主机名或ip地址名,,我在设置Jobbole这个连接时使用的是localhost。

②就是url_object_id得有一个默认值,我感觉没设置成主键会有小问题的,如果重复了怎么办。

所以我就将url_object_id设置为主键,但是再爬取时只能爬取到第一条数据。并报错。



现在还不知道如何解决这个问题。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Scrapy提供了一个方便的Pipeline来将数据存储到MySQL数据库中。要将数据存储到MySQL中,您需要安装pymysql库。可以使用以下命令来安装: ``` pip install pymysql ``` 然后,在项目的settings.py文件中添加以下代码: ```python ITEM_PIPELINES = { 'myproject.pipelines.MySQLPipeline': 300, } MYSQL_HOST = 'localhost' # MySQL服务器地址 MYSQL_DBNAME = 'mydatabase' # MySQL数据库名 MYSQL_USER = 'myuser' # MySQL用户名 MYSQL_PASSWD = 'mypassword' # MySQL密码 ``` 接下来,您需要创建名为MySQLPipeline.py的文件,并在其中编写将数据存储到MySQL的代码: ```python import pymysql class MySQLPipeline(object): def __init__(self, host, dbname, user, password): self.host = host self.dbname = dbname self.user = user self.password = password @classmethod def from_crawler(cls, crawler): return cls( host=crawler.settings.get('MYSQL_HOST'), dbname=crawler.settings.get('MYSQL_DBNAME'), user=crawler.settings.get('MYSQL_USER'), password=crawler.settings.get('MYSQL_PASSWD') ) def open_spider(self, spider): self.conn = pymysql.connect(host=self.host, user=self.user, password=self.password, db=self.dbname) self.cursor = self.conn.cursor() def close_spider(self, spider): self.conn.commit() self.conn.close() def process_item(self, item, spider): sql = "INSERT INTO mytable (column1, column2) VALUES (%s, %s)" self.cursor.execute(sql, (item['field1'], item['field2'])) return item ``` 在上面的代码中,我们使用了pymysql库来连接到MySQL数据库。在open_spider()方法中我们打开了数据库连接,并使用process_item()方法将数据插入到MySQL中。在close_spider()方法中,我们提交了所有的更改并关闭了数据库连接。 最后,确保您的Spider中的Item具有相应的字段名称,以便可以在process_item()方法中访问它们。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值