Mysql数据库写入方式,引入pymysql安装包,下面的是同步写入数据
import requests
import pymysql
class MysqlPipeline(object):
def open_spider(self, spider):
# 连接mysql数据库
self.conn = pymysql.connect(
host='127.0.0.1',
port=3306,
user='root',
password='123456',
db='books',
charset='utf8'
)
self.cursor = self.conn.cursor()
def process_item(self, item, spdier):
self.cursor.execute("INSERT INTO novel(book_name, book_status,book_type,book_img_src)VALUES(%s,%s,%s,%s)",(item['book_name'], item['book_status'], item['book_type'], item['book_img_src'][0]))
self.conn.commit()
return item
def close_spider(self, spider):
self.cursor.close()
self.conn.close()
Mysql异步数据库写入,需要引入twisted安装包中的adbapi模块
import requests
import pymysql
from twisted.enterprise import adbapi
# 异步写入数据
# adbapi 用于异步操作数据库的模块
class AsyncWriteToMysql(object):
# Async异步
def __init__(self):
# 准备链接数据库的参数
# 创建字典的方式:{k:v} dict(k=v) {字典生成式}
prams = dict(
host='127.0.0.1',
port=3306,
user='root',
password='123456',
db='bks',
charset='utf8',
# use_unicode是否使用unicode字符编码
use_unicode=True,
# 使用字典类型游标
cursorclass=pymysql.cursors.DictCursor
)
# 创建连接池对象
# 1.用来操作mysql的第三方包名称
# 2.链接数据库需要的参数
self.db_pool = adbapi.ConnectionPool('pymysql', **prams)
def process_item(self, item, spdier):
# 让连接池执行任务
# 1.执行的函数 2.执行的函数需要的参数
# 异步执行任务,任务执行完成之后,会返回执行的结果
result = self.db_pool.runInteraction(self.insert_item, item)
# 给执行结果添加错误回调函数
result.addErrback(self.insert_error, item)
return item
def insert_error(self, fail, item):
print(f'插入数据失败,原因:{fail.value}, 数据:{item["book_name"]}')
# 执行插入数据的函数
# 1.cursor是一个必要的参数
def insert_item(self, cursor, item):
# 数据、游标
cursor.execute('INSERT INTO novel(book_name, book_status, book_type, book_img_src)VALUES(%s,%s,%s,%s)', (item['book_name'],item['book_status'],item['book_type'],item['book_img_src'][0]))
**
workbook创建工作簿数据库,引入xlwt模块
**
class ExcelPipeline(object):
# 创建workbook,创建sheet表,写入表头,计数 写入指定行数据
def open_spider(self, spider):
self.workbook = xlwt.Workbook(encoding='utf-8')
self.sheet = self.workbook.add_sheet('data')
self.sheet.write(0, 0, 'book_name')
self.sheet.write(0, 1, 'book_status')
self.sheet.write(0, 2, 'book_type')
self.sheet.write(0, 3, 'book_img_src')
# 计数
self.count = 0
def process_item(self, item, spider):
self.count += 1
self.sheet.write(self.count, 0, item['book_name'])
self.sheet.write(self.count, 1, item['book_status'])
self.sheet.write(self.count, 2, item['book_type'])
self.sheet.write(self.count, 3, item['book_img_src'][0])
self.workbook.save('novel.xls')
return item