Scrapy将数据存入excel和MySQL数据库中

一:Scrapy将爬到的数据存入MySQL数据库中

1.导入pymysql第三方库

pip install pymysql

2.连接数据库(itempipeline.py)

实现数据库的连接一般分为三个步骤:建立连接,操作数据,提交事务,关闭数据库。基本方法如下:

class Spider01Pipeline:     #连接数据库
    def __init__(self):
        pass

    def process_item(self,item,spider):   #操作数据
        pass

    def close_spider(self,spider):       #提交事务,关闭数据库
        pass

注意:Spider01Pipeline类里面的方法名不能错,不然爬虫框架不能识别。
在加入数据之前,要对数据在MySQL数据库中进行建表。

1.数据库进行连接

class Spider01Pipeline:
    def __init__(self):
        self.db_conn = pymysql.connect(host='localhost', user='root', password='123456', database='pachong',charset='utf8',use_unicode=True)   #连接数据库
        self.db_cur = self.db_conn.cursor()     #创建游标
        print('连接成功!')

host:服务器ip
user:用户名(不同的用户名权限不一样,可去MySQL里面修改查看)
password:登录MySQL的密码
database:数据库的名称
charset:字符集(utf8)
use_unicode:使用Unicode字符集并且设置字符编码为utf-8

2.操作(添加)数据

    def process_item(self,item,spider):
        value = (item['name'],item['content'])
        sql = "insert into mingrenmingyan(name,content) values (%s,%s)"   #为SQL语法,数据顺序要和建表一致
        self.db_cur.execute(sql,value)
        self.db_conn.commit()
        return item

self.db_cur.execute:进行数据插入(单条)
注:一定要返回数据项 return item ,不然后续找不到数据项

3.关闭数据库

    def close_spider(self,spider):
        self.db_cur.close()     #关闭游标
        self.db_conn.close()    #关闭数据库

4.完成Spider01Pipeline的编写后,需要在settings.py文件中找到管道配置并开启

ITEM_PIPELINES = {
   'spider01.pipelines.Spider01Pipeline': 300,
}

二:Scrapy将爬到的数据存入excel中

也分为三个步骤:建立工作表,操作数据,关闭excel

1.导入操作excel的第三方库openpyxl

pip install openpyxl

2.创建工作簿

1.创建工作表

class Spider02Pipeline:
    def __init__(self):
        self.wb = openpyxl.Workbook()    #工作簿
        # self.ws = self.wb.create_sheet() #创建工作表
        self.ws = self.wb.active         #激活默认工作表
        self.ws.title = '名人名言'         #工作表的名称
        self.ws.append(('姓名','名言'))    #加入表头

注:这个类也是在数据管道文件中,所以类名不能一样

2.操作数据

    def process_item(self,item,spider):
        name = item.get('name',' ')
        content = item.get('content',' ')
        self.ws.append((name,content))
        return item

3.保存文件

    def close_spider(self, spider):
        self.wb.save('名人名言.xlsx')    #文件名称存为名人名言

4.完成Spider02Pipeline的编写后,需要在settings.py文件中找到管道配置并开启

ITEM_PIPELINES = {
   'spider01.pipelines.Spider02Pipeline':290,
}

三:实例

使用CrawlSpider模板

http://quotes.toscrape.com/这个网站为例

爬虫文件quotes.py

import scrapy
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule


class QuotesSpider(CrawlSpider):
    name = 'quotes'
    allowed_domains = ['quotes.toscrape.com']
    start_urls = ['http://quotes.toscrape.com/']
    rules = (
        Rule(LinkExtractor(restrict_xpaths=(r'//*[@class = "next"]/a')), callback='parse_item', follow=True), 
    ) #LinkExtractor为连接提取器,callback:回调方法,follow:是否跟进。当callback为None,默认fallow为True,否则Flase
    def parse_item(self, response):
        item = {}
        for row in response.xpath('/html/body/div/div[2]/div[1]/div'):
            item['content'] = row.xpath('span[1]/text()').get()
            item['name'] = row.xpath('span[2]/small/text()').get()
            # print(item)
            yield item

数据管道文件pipelines.py(同时将数据写入数据库和excel文件)


import pymysql
import openpyxl

class Spider01Pipeline:
    def __init__(self):
        self.db_conn = pymysql.connect(host='localhost', user='root', password='123456', database='pachong',charset='utf8',use_unicode=True)
        self.db_cur = self.db_conn.cursor()
        print('连接成功!')

    def process_item(self,item,spider):
        value = (item['name'],item['content'])
        sql = "insert into mingrenmingyan(name,content) values (%s,%s)"
        self.db_cur.execute(sql,value)
        self.db_conn.commit()
        return item

    def close_spider(self,spider):
        self.db_cur.close()
        self.db_conn.close()

class Spider02Pipeline:
    def __init__(self):
        self.wb = openpyxl.Workbook()    #工作簿
        # self.ws = self.wb.create_sheet() #创建工作表
        self.ws = self.wb.active         #激活默认工作表
        self.ws.title = '名人名言'         #工作表的名称
        self.ws.append(('姓名','名言'))    #加入表头

    def process_item(self,item,spider):
        name = item.get('name',' ')
        content = item.get('content',' ')
        self.ws.append((name,content))
        return item

    def close_spider(self, spider):
        self.wb.save('名人名言.xlsx')

文件配置settings.py

BOT_NAME = 'spider01'
USER_AGENTS = [
        "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Win64; x64; Trident/5.0; .NET CLR 3.5.30729; .NET CLR 3.0.30729; .NET CLR 2.0.50727; Media Center PC 6.0)",
        "Mozilla/5.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; .NET CLR 1.0.3705; .NET CLR 1.1.4322)",
        "Mozilla/4.0 (compatible; MSIE 7.0b; Windows NT 5.2; .NET CLR 1.1.4322; .NET CLR 2.0.50727; InfoPath.2; .NET CLR 3.0.04506.30)",
        "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN) AppleWebKit/523.15 (KHTML, like Gecko, Safari/419.3) Arora/0.3 (Change: 287 c9dfb30)",
        "Mozilla/5.0 (X11; U; Linux; en-US) AppleWebKit/527+ (KHTML, like Gecko, Safari/419.3) Arora/0.6",
        "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.2pre) Gecko/20070215 K-Ninja/2.1.1",
        "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9) Gecko/20080705 Firefox/3.0 Kapiko/3.0",
        "Mozilla/5.0 (X11; Linux i686; U;) Gecko/20070322 Kazehakase/0.4.5"]  #让浏览器认为你是人为登录

ROBOTSTXT_OBEY = False     #不遵守爬虫协议
LOG_LEVEL='WARNING'        #不开启日志

DOWNLOAD_DELAY = 3
RANDOMIZE_DOWNLOAD_DELAY=True      #开启随机时间延迟,防止网站屏蔽IP

ITEM_PIPELINES = {
   'spider01.pipelines.Spider01Pipeline': 300,
   'spider01.pipelines.Spider02Pipeline':290,
}#开启数据管道,同时将数据写入MySQL和excel文件中,字典的值越小优先级越高。

到这里,整个爬虫程序就写完了,下面只需要在终端开启爬虫

scrapy crawl quotes

*注:crawl后面跟的是运行爬虫的名称

posted @ 2023-05-17 19:14  杨三火啥也不会  阅读(254)  评论(0编辑  收藏  举报