03.5.1. 存储数据到json文件

  1. class StudyPipeline(object):
  2. # 构造方法
  3. def __init__(self):
  4. self.f = None # 定义一个文件描述符属性
  5. # 下列都是在重写父类的方法:
  6. # 开始爬虫时,执行一次
  7. def open_spider(self, spider):
  8. print('爬虫开始')
  9. # 打开一个json文件用于接收json方法写入的数据
  10. self.f = open('douban.json', 'w', encoding='utf-8')
  11. # 专门处理item对象
  12. # 因为该方法会被执行调用多次,所以文件的开启和关闭操作写在了另外两个只会各自执行一次的方法中。
  13. def process_item(self, item, spider):
  14. # 将jsondumps方法获取的数据赋值给content
  15. # 为什么将item转换成字典呢,因为这个item返回的值是scrapy特有的存储,python是不识别的
  16. content = json.dumps(dict(item), ensure_ascii=False)+",\n"
  17. self.f.write(content)
  18. # 传递到下一个被执行的管道类,一定要返回item不然就会出错
  19. return item
  20. # 关闭爬虫
  21. def close_spider(self, spider):
  22. print('爬虫结束')
  23. self.f.close()

03.5.2. 存储数据到Mysql数据库

  1. # 管道文件中的一个管道类对应的是将数据存储到一种平台
  2. # 爬虫文件提交的item只会给管道文件中第一个被执行的管道类接受
  3. # process_item的return item表示item传递到下一个被执行的管道类
  4. # 将数据存储到数据库
  5. class mysqlPipeline(object):
  6. # pymysql插入数据简单用法
  7. # 1. 连接connect = pymysql.connect("各种配置")
  8. # 2. 创建游标 cursor = connect.cursor()
  9. # 3. 执行sql语句 cursor.execute("sql")
  10. # 4. 提交 connect.commit()
  11. # 5. 关闭游标 cursor.close
  12. # 6. 关闭数据库 connect.close
  13. # 注意:56顺序不可颠倒!
  14. # 构造方法
  15. def __init__(self):
  16. self.conn = None # 定义一个文件描述符属性
  17. self.cursor = None
  18. self.num = 0
  19. # 下列都是在重写父类的方法:
  20. # 开始爬虫时,执行一次
  21. def open_spider(self, spider):
  22. # 首先初始化构建一个建表sql
  23. sql = '''
  24. create table movie
  25. (
  26. movie_name varchar(500) ,
  27. movie_link varchar(500) ,
  28. star varchar(500),
  29. quote varchar(500)
  30. )
  31. '''
  32. # 连接mysql数据库
  33. # 注:此处的配置建议写在setting配置中
  34. self.conn = pymysql.connect(
  35. host='192.168.0.157', # IP地址
  36. port=3306, user='root', # 端口,账号
  37. password='123456', # 密码
  38. database='movie_top250', # 数据库名字
  39. charset='utf8') # 字符集
  40. cursor = self.conn.cursor() # 建立游标
  41. cursor.execute(sql) # execute方法执行sql语句
  42. self.conn.commit() # commit方法提交一个执行语句(只有插入和更新才需要哦)
  43. print('爬虫数据库开始')# printpython3里需要加()
  44. # 专门处理item对象
  45. # 因为该方法会被执行调用多次,所以文件的开启和关闭操作写在了另外两个只会各自执行一次的方法中。
  46. def process_item(self, item, spider):
  47. # 为了方便理解,这里将item返回的数据赋值给下边插入语句使用
  48. movie_name = item['movie_name']
  49. movie_link = item['movie_link']
  50. star = item['star']
  51. quote = item['quote']
  52. # 执行sql前要建立一个游标,在上边方法已经连接数据库了所以这里不需要重连
  53. self.cursor = self.conn.cursor()
  54. # 进行mysql的异常捕获
  55. try:
  56. # 插入数据时候一定要对应好行和列
  57. # 下方%s格式化字符串可以用format,自行测试
  58. self.cursor.execute('''
  59. insert into movie
  60. values(%s,%s,%s,%s)''', (movie_name, movie_link, star, quote))
  61. self.conn.commit() # 提交上方的插入sql
  62. except Exception as e:
  63. print(e)
  64. self.conn.rollback() # 回滚
  65. return item
  66. # 关闭游标,关闭数据库连接
  67. def close_spider(self, spider):
  68. self.cursor.close()
  69. self.conn.close()
  70. print('爬虫数据入库结束')