第一个实践笔记 基础模板
setting.py
BOT_NAME = 'bgmSpider'
SPIDER_MODULES = ['bgmSpider.spiders']
NEWSPIDER_MODULE = 'bgmSpider.spiders'
ROBOTSTXT_OBEY = True
ITEM_PIPELINES = {
'bgmSpider.pipelines.BgmspiderPipeline': 300,
}
MYSQL_HOST = YOUR_HOST
MYSQL_DBNAME = YOUR_DBNAME
MYSQL_USER = YOUR_USERNAME
MYSQL_PASSWD = YOUR_PASSWD
pipeline.py
from scrapy.pipelines.files import FilesPipeline
from urllib.parse import urlparse
from bgmSpider import settings
import pymysql
class BgmspiderPipeline(object):
def __init__(self):
self.connect = pymysql.connect(
host=settings.MYSQL_HOST,
db=settings.MYSQL_DBNAME,
user=settings.MYSQL_USER,
passwd=settings.MYSQL_PASSWD,
use_unicode=True)
self.cursor = self.connect.cursor()
def process_item(self, item, spider):
if spider.name == 'bgm':
self.cursor.execute(
'insert ignore into bgm (bgm_name,bgm_cat,bgm_tag,bgm_time,bgm_music,bgm_link,bgm_img) values (%s,%s,%s,%s,%s,%s,%s)',
(item['bgm_name'],item['bgm_cat'],item['bgm_tag'],item['bgm_time'],item['bgm_music'],
item['bgm_link'],item['bgm_img']))
self.connect.commit()
return item
第二个实践笔记
scrapy同步存储mysql数据基本items.py
# -*- coding: utf-8 -*-
# Define here the models for your scraped items
#
# See documentation in:
# https://docs.scrapy.org/en/latest/topics/items.html
import scrapy
class Scrapydemo11Item(scrapy.Item):
# define the fields for your item here like:
# name = scrapy.Field()
phone=scrapy.Field()
price=scrapy.Field()
基本pipeline.py
#第一步必须做的是是引入pymysql模块
import pymysql
class BasicdemoPipeline(object):
def open_spider(self, spider):
db = spider.settings.get('MYSQL_DB_NAME','test1')
host = spider.settings.get('MYSQL_HOST', 'localhost')
port = spider.settings.get('MYSQL_PORT', 3306)
user = spider.settings.get('MYSQL_USER', 'root')
passwd = spider.settings.get('MYSQL_PASSWORD', '')
#第二步是引入连接数据库,pymysql.connect过程中传入多个参数:数据库主机名(默认为本地主机),数据库登录名(默认为当前用户),数据库密码(默认为空),要打开的数据库名称(无默认,可缺省),MySQL使用的TCP端口(默认为3306,可缺省),数据库字符编码(可缺省),self后边的连接名称可以自取名
self.db_conn =pymysql.connect(host=host, port=port, db=db, user=user, passwd=passwd, charset='utf8')
#第三步 获取游标self.连接名.cursor(),游标就像是鼠标一样,后续操作数据库全部靠游标,使用游标的execute命令来执行。
self.db_cur = self.db_conn.cursor()
def close_spider(self, spider):
#第五步 提交数据库执行
self.db_conn.commit()
#第六步 关闭数据库
self.db_conn.close()
def process_item(self, item, spider):
self.insert_db(item)
return item
def insert_db(self, item):
values = (
item['title'][0],
item['article'][0],
)
print("Insert 成功了")
sql = 'INSERT INTO boods(dd,ff) VALUES(%s,%s)'
#第四步 用游标执行数据库命令
self.db_cur.execute(sql, values)
setting.py
ITEM_PIPELINES = {
'scrapydemo11.pipelines.Scrapydemo11Pipeline': 300,
}
#激活pipelines
爬虫文件要与数据库sql语句相一致。另外创建数据库的时候一定要定义一个字段当,属性int,自动递增。如下图
第二个实践笔记
异步操作存入数据库
关键的是pipeline.py文件
# -*- coding: utf-8 -*-
import pymysql
# 使用twsited异步IO框架,实现数据的异步写入。
from pymysql import cursors
from twisted.enterprise import adbapi
class BasicdemoTPipeline(object):
def __init__(self):
dbparams = {
'host': 'localhost',
'port': 3306,
'user': 'root',
'password': '',
'database': 'test1',
'charset': 'utf8',
'cursorclass': cursors.DictCursor # 指定cursor的类
}
#初始化数据库连接池,参数1是mysql的驱动,参数2是连接mysql的配置信息
self.db_pool = adbapi.ConnectionPool('pymysql', **dbparams)
#sql语言的空值
self._sql = None
@property
def sql(self):
if not self._sql:
self._sql = 'INSERT INTO boods(dd,ff) VALUES(%s,%s)'
return self._sql
return self._sql
def process_item(self, item, spider):
#操作数据,将数据写入数据库
#如果是同步写入的话,使用的是cursor.execute(),commit()
#异步存储的方式:函数方式pool.map(self.insert_db,[1,2])
query = self.db_pool.runInteraction(self.insert_db,item)
query.addErrback(self.handle_error, item, spider)
def insert_db(self,cursor, item):
for i in range(len(item['title'])) :
values = (
item['title'][i],
item['article'][i],
)
print("Insert 成功了")
cursor.execute(self.sql, values)
def handle_error(self,error,item,spider):
print('='*10 + "error" + '='*10)
print(error)
print('=' * 10 + "error" + '=' * 10)