爬取失信人名单

  1. 实现步骤

    • 创建爬虫项目
    • 根据需求定义数据模型
    • 实现爬虫
    • 保存爬取的数据
    • 实现随机user-agent和代理ip下载器中间件,解决ip反爬
  2. 实现爬虫的具体步骤

  3. 保存失信名单信息

    1. 创建数据库,创建表

    2. 在settings中配置数据库信息

      • host、port、db、user、password
    3. 实现管道类

      1. 在open_spider中,建立数据库连接,获取cursor

        • def open_spider(self, spider):
              """不用做判断,因为三只爬虫的爬取结果全部放到同一个数据库里边"""
              # 创建数据库连接
              self.connection = pymysql.connect(host=MYSQL_HOST, port=MYSQL_PORT, db=MYSQL_DB,
                                                user=MYSQL_USER, password=MYSQL_PASSWORD)
              # 获取游标
              self.cursor = self.connection.cursor()
      2. 在close_spider中,关闭cursor,关闭数据库连接

        • def close_spider(self, spider):
              # 关闭游标
              self.cursor.close()
              # 关闭连接
              self.connection.close()
      3. 在process_item中,如果数据不存在,保存数据

        • def process_item(self, item, spider):
              # 存储过程,最重要是判断数据是否已经存在
              # 判断数据是否已经存在
              if item['age'] == 0:
                  select_count_sql = "select count(1) from dishonest where name='{}' and area='{}'".format(item['name'],
                                                                                                           item['area'])
              else:
                  select_count_sql = "select count(1) from dishonest where card_num='{}'".format(item['card_num'])
          
              # 执行查询
              self.cursor.execute(select_count_sql)
              count = self.cursor.fetchone()[0]    # 游标会获取的结果是列表形式
          
              # 根据查询结果,决定是否插入数据
              if count == 0:
                  keys, values = zip(*dict(item).items())
                  insert_sql = 'insert into dishonest ({}) values ({})'.format(
                      ','.join(keys),
                      ','.join(['%s']*len(values))
                  )
                  self.cursor.execute(insert_sql,values)
                  self.connection.commit()
                  spider.logger.info('插入数据')
              else:
                  spider.logger.info('数据重复')
    4. 在settings.py中开启管道

猜你喜欢

转载自www.cnblogs.com/hui-code/p/12030353.html
今日推荐