利用scrapy将爬到的数据保存到mysql(防止重复)


Posted in Python onMarch 31, 2018

前言

本文主要给大家介绍了关于scrapy爬到的数据保存到mysql(防止重复)的相关内容,分享出来供大家参考学习,下面话不多说了,来一起看看详细的介绍吧。

1.环境建立

     1.使用xmapp安装php, mysql ,phpmyadmin

     2.安装python3,pip

     3.安装pymysql

     3.(windows 略)我这边是mac,安装brew,用brew 安装scrapy

2.整个流程

     1. 创建数据库和数据库表,准备保存

     2.写入爬虫目标URL,进行网络请求

     3.对爬返回数据进行处理,得到具体数据

     4.对于具体数据保存到数据库中

2.1.创建数据库

首先创建一个数据库叫scrapy,然后创建一个表article,我们这里给body加了唯一索引,防止重复插入数据

--
-- Database: `scrapy`
--
 
-- --------------------------------------------------------
 
--
-- 表的结构 `article`
--
 
CREATE TABLE `article` (
 `id` int(11) NOT NULL,
 `body` varchar(200) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL,
 `author` varchar(50) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL,
 `createDate` datetime NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
 
 
--
-- Indexes for table `article`
--
ALTER TABLE `article`
 ADD PRIMARY KEY (`id`),
 ADD UNIQUE KEY `uk_body` (`body`);

利用scrapy将爬到的数据保存到mysql(防止重复)

弄好以后是这样的。

2.2 先看下整个爬虫项目的结构

利用scrapy将爬到的数据保存到mysql(防止重复)

quotes_spider.py是核心,负责对网络请求和对内容进行处理,然后对整理好的内容抛给pipelines进行具体处理,保存到数据库中,这样不会影响速度。

其他的看 图说明

2.2 写入爬虫目标URL,进行网络请求

import scrapy
from tutorial.items import TutorialItem
class QuotesSpider(scrapy.Spider):
 name = "quotes"
 def start_requests(self):
  url = 'http://quotes.toscrape.com/tag/humor/'
  yield scrapy.Request(url)
 def parse(self, response):
  item = TutorialItem()
  for quote in response.css('div.quote'):
   item['body'] = quote.css('span.text::text').extract_first()
   item['author'] = quote.css('small.author::text').extract_first()
   yield item
  next_page = response.css('li.next a::attr("href")').extract_first()
  if next_page is not None:
   yield response.follow(next_page, self.parse)

start_requests 就是要写入具体要爬的URL

parse就是核心的对返回的数据进行处理的地方,然后以item的形式抛出,接下来定义好下一个要爬的内容 

2.3  items

# -*- coding: utf-8 -*-
# Define here the models for your scraped items
#
# See documentation in:
# https://doc.scrapy.org/en/latest/topics/items.html
import scrapy
class TutorialItem(scrapy.Item):
 body = scrapy.Field()
 author = scrapy.Field()
 pass

2.4 pipelines

# -*- coding: utf-8 -*-
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html
import pymysql
import datetime
from tutorial import settings
import logging
class TutorialPipeline(object):
 def __init__(self):
  self.connect = pymysql.connect(
   host = settings.MYSQL_HOST,
   db = settings.MYSQL_DBNAME,
   user = settings.MYSQL_USER,
   passwd = settings.MYSQL_PASSWD,
   charset = 'utf8',
   use_unicode = True
  )
  self.cursor = self.connect.cursor(); 
 def process_item(self, item, spider):
  try:
   self.cursor.execute(
    "insert into article (body, author, createDate) value(%s, %s, %s) on duplicate key update author=(author)",
    (item['body'],
     item['author'],
     datetime.datetime.now()
     ))
   self.connect.commit()
  except Exception as error:
   logging.log(error)
  return item
 def close_spider(self, spider):
  self.connect.close();

2.5 配置

ITEM_PIPELINES = {
 'tutorial.pipelines.TutorialPipeline':300
}
MYSQL_HOST = 'localhost'
MYSQL_DBNAME = 'scrapy'
MYSQL_USER = 'root'
MYSQL_PASSWD = '123456'
MYSQL_PORT = 3306

3.启动爬虫

scrapy crawl quotes

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对三水点靠木的支持。

Python 相关文章推荐
Python BeautifulSoup中文乱码问题的2种解决方法
Apr 22 Python
简析Python的闭包和装饰器
Feb 26 Python
python中string模块各属性以及函数的用法介绍
May 30 Python
Python中线程的MQ消息队列实现以及消息队列的优点解析
Jun 29 Python
Python字符串处理实现单词反转
Jun 14 Python
python实现logistic分类算法代码
Feb 28 Python
keras 权重保存和权重载入方式
May 21 Python
Python 如何展开嵌套的序列
Aug 01 Python
python利用递归方法实现求集合的幂集
Sep 07 Python
Python使用socket_TCP实现小文件下载功能
Oct 09 Python
Python项目实战之使用Django框架实现支付宝付款功能
Feb 23 Python
python b站视频下载的五种版本
May 27 Python
python 通过xml获取测试节点和属性的实例
Mar 31 #Python
Python Xml文件添加字节属性的方法
Mar 31 #Python
Python简单生成随机数的方法示例
Mar 31 #Python
用python 批量更改图像尺寸到统一大小的方法
Mar 31 #Python
使用Python读取安卓手机的屏幕分辨率方法
Mar 31 #Python
python获取网页中所有图片并筛选指定分辨率的方法
Mar 31 #Python
python如何将图片转换为字符图片
Aug 19 #Python
You might like
PHP Zip压缩 在线对文件进行压缩的函数
2010/05/26 PHP
用php实现选择排序的解决方法
2013/05/04 PHP
PHP swfupload图片上传的实例代码
2013/09/30 PHP
php遍历目录与文件夹的多种方法详解
2013/11/14 PHP
PHP捕获Fatal error错误的方法
2014/06/11 PHP
thinkphp多表查询两表有重复相同字段的完美解决方法
2016/09/22 PHP
jQuery+php简单实现全选删除的方法
2016/11/28 PHP
win10下 php安装seaslog扩展的详细步骤
2020/12/04 PHP
基于逻辑运算的简单权限系统(实现) JS 版
2007/03/24 Javascript
JQuery给元素添加/删除节点比如select
2013/04/02 Javascript
javascript中简单的进制转换代码实例
2013/10/26 Javascript
Js实现滚动变色的文字效果
2014/06/16 Javascript
jquery插件jSignature实现手动签名
2015/05/04 Javascript
《JavaScript函数式编程》读后感
2015/08/07 Javascript
jQuery实现订单提交页发送短信功能前端处理方法
2016/07/04 Javascript
js中值引用和地址引用实例分析
2019/06/21 Javascript
[02:44]DOTA2英雄基础教程 克林克兹
2014/01/15 DOTA
[01:48]完美圣典齐天大圣至宝宣传片
2016/12/17 DOTA
将图片文件嵌入到wxpython代码中的实现方法
2014/08/11 Python
python jieba分词并统计词频后输出结果到Excel和txt文档方法
2018/02/11 Python
Flask 让jsonify返回的json串支持中文显示的方法
2018/03/26 Python
python3调用百度翻译API实现实时翻译
2018/08/16 Python
Python3 jupyter notebook 服务器搭建过程
2018/11/30 Python
python爬虫获取小区经纬度以及结构化地址
2018/12/30 Python
浅析Django中关于session的使用
2019/12/30 Python
使用 Python 处理3万多条数据只要几秒钟
2020/01/19 Python
python 中的paramiko模块简介及安装过程
2020/02/29 Python
Python 没有main函数的原因
2020/07/10 Python
python IP地址转整数
2020/11/20 Python
BISSELL官网:北美吸尘器第一品牌
2019/03/14 全球购物
超市优秀员工事迹材料
2014/05/01 职场文书
2015年企业员工工作总结范文
2015/05/21 职场文书
试用期转正工作总结2015
2015/05/28 职场文书
电工生产实习心得体会
2016/01/22 职场文书
html+css实现分层金字塔的实例
2021/06/02 HTML / CSS
Golang 语言控制并发 Goroutine的方法
2021/06/30 Golang