• Python爬虫之Js逆向案例(10)-爬虫数据批量写入mysql数据库


    最近收到小伙伴们的私信,说如何将爬取的数据批量存到数据库中?数据入库也是童鞋们必须掌握的技能!数据回来之后,肯定需要存放,实效高、数量少的可能大多存放在cvs文件中,通常情况都是要存放到数据库的!

    1. 数据库
    2. 准备数据库链接实例
    3. 结果演示

    一.数据库

    本案例使用mysql数据库,版本我这边测试了两个:v5.7v8.0.30,不需要那么多,安装一个就行!下面介绍一下我这边的操作!

    1. 阿里云服务器1台;(新账号的话可以免费使用1个月。我这边之前就买了,在上面安装的mysql5.7docker镜像版,网上帖子比较多,这里就不一一介绍了,安装过程很容易找到,就不重复了),没有云服务器的,也可以本地安装一个,练习,无所谓。

    2.安装mysql(安装mysql的时候很头疼,大家可能也会遇到账号问题,网上搜方案都能解决)

    3.DBeaver
    数据库的可视化工具,免费的。还一个好用的工具navicat,这个是收费的,如果能找到破解版的也可以用这个,都挺好用。

    二.准备数据库链接实例并实现

    新建文件DBPool.py

    import pymysql
    from dbutils.pooled_db import PooledDB
    
    
    class MySQL:
    	# 你的数据库host,如何是云服务器,填写你的服务器地址,如果是本地填写localhost
        host = 'XXX.XXX.XXX.XXX' 
    	# 数据库账号
        user = 'root'
        # 数据库端口号,一般默认3306
        port = 3306
        # 数据库账号
        pasword = 'XXXX'
        # 数据库
        db = 'XXX'
        charset = 'utf8'
    
        pool = None
        limit_count = 3  # 最低预启动数据库连接数量
    
        def __init__(self):
            self.pool = PooledDB(pymysql,
                                 self.limit_count,
                                 host=self.host,
                                 user=self.user,
                                 passwd=self.pasword,
                                 db=self.db,
                                 port=self.port,
                                 charset=self.charset,
                                 use_unicode=True)
    
        def select(self, sql):
            conn = self.pool.connection()
            cursor = conn.cursor()
            cursor.execute(sql)
            result = cursor.fetchall()
            cursor.close()
            conn.close()
            return result
    	# 单个插入
        def insert(self, sql):
            conn = self.pool.connection()
            cursor = conn.cursor()
            try:
                cursor.execute(sql)
                conn.commit()
                return {'result': True, 'id': int(cursor.lastrowid)}
            except Exception as err:
                conn.rollback()
                return {'result': False, 'err': err}
            finally:
                cursor.close()
                conn.close()
    
    	# 批量插入
        def insertMany(self, sql, datas):
            conn = self.pool.connection()
            cursor = conn.cursor()
            try:
                cursor.executemany(sql, datas)
                conn.commit()
                return {'result': True, 'id': int(cursor.lastrowid)}
            except Exception as err:
                conn.rollback()
                return {'result': False, 'err': err}
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66

    在py文件中导入数据库连接实例,

    from DBPool import MySQL
    
    • 1

    实例化数据库对象

    mysql = MySQL()
    
    • 1

    爬取到的数据进行处理

    
    def get_fetch(first, last):
        for page in range(first, last + 1):
            data.update({"page": page})
            params = json.dumps(data)
            # list是爬取到的列表数据,格式为:[{}、{}、{}],一个list有20条数据
            list = requests.post(url, headers=headers,
                                 data=params).json()['data']['item']
            sql = "INSERT INTO schools(address,admissions,answerurl,belong,central,city_id,city_name,code_enroll,colleges_level,county_id,county_name,department,doublehigh,dual_class,dual_class_name,f211,f985,id,is_logo,is_recruitment,is_top,level,level_name,name,nature,nature_name,province_id,province_name,rank) values(%s,%s,%s,%s,%s,%s,%s, %s,%s, %s,%s, %s,%s,%s,%s, %s,%s,%s, %s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)"
            
            # datas用于存放将要插入数据库的数据
            datas = []
            # print(page, len(list))
    
    		# 遍历list,
            for item in list:
            	# 注意这的数据写法
                value = [
                    item['address'],
                    item['admissions'],
                    item['answerurl'],
                    item['belong'],
                    item['central'],
                    item['city_id'],
                    item['city_name'],
                    item['code_enroll'],
                    item['colleges_level'],
                    item['county_id'],
                    item['county_name'],
                    item['department'],
                    item['doublehigh'],
                    item['dual_class'],
                    item['dual_class_name'],
                    item['f211'],
                    item['f985'],
                    item['id'],
                    item['is_logo'],
                    item['is_recruitment'],
                    item['is_top'],
                    item['level'],
                    item['level_name'],
                    item['name'],
                    item['nature'],
                    item['nature_name'],
                    item['province_id'],
                    item['province_name'],
                    item['rank'],
                ]
                datas.append(value)
            # 使用批量插入的insertMany进行处理
            res = mysql.insertMany(sql, datas)
            
    		# 注意需要根据返回的结果判断是否插入成功
            if (res['result']):
                print(page, "数据插入成功!")
            else:
            	## 打印失败的页码和错误信息
                print(page, res)
            
            # 防止爬的太快被封,设置随机休眠时间
            sleepTime = random.random() * 10
            print('休眠:{}秒'.format(int(sleepTime)))
            time.sleep(sleepTime)
    
    
    if __name__ == '__main__':
        # 请求n页数据
        get_fetch(1, 1000)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68

    三.结果演示

    在这里插入图片描述


    后期会持续分享爬虫案例-100例,不想自己造轮子的同学可加入我的知识星球,有更多技巧、案例注意事项、案例坑点终结、答疑提问特权等你哦!!!

    欢迎加入「python、爬虫、逆向Club」知识星球

  • 相关阅读:
    C++学习日记——宏函数和内联函数
    算法训练——双指针专题
    计算机操作系统——概述(课程笔记)
    Windows下编译android版ijkplayer
    Hadoop系列——Hadoop集群安装day2-1
    虹科示波器 | 汽车免拆检修 | 2010款江铃陆风X8车发动机怠速抖动、加速无力
    22-Docker-常用命令详解-docker pull
    vue slot插槽
    【三等奖方案】小样本数据分类任务赛题「复兴15号」团队解题思路
    狂神说-Springboot的入门初探
  • 原文地址:https://blog.csdn.net/li11_/article/details/126671015