爬虫存sqllite3的方法

我们写爬虫都是将爬取得数据进行数据库存储,下面为大家介绍一下存sqllite的方法,本人亲测

 http://example.webscraping.com   国家网页进行演练

注意!!!我的scrapy名字叫scrapy_item,不和我一样就要仔细看下我settings代码说明

在scrapy框架的spiders文件夹中添加一个TextSpider.py文件(py文件名大家可以自由写)源码为

# -*- coding: utf-8 -*-    # python2x的添加此行
import scrapy
from scrapy import Request

from scrapy_item.items import ScrapyItemItem   # 此处是你scrapy里的items文件


class TestspiderSpider(scrapy.Spider):
    name = 'TestSpider'  # 爬虫名称,scrapy crawl 后面的名称必须跟这个对应
    allowed_domains = ['webscraping.com']  # 允许爬取的域名
    start_urls = ['http://example.webscraping.com']  # 种子网址
    is_first = True

    def parse(self, response):  # 种子网址爬取成功后系统默认调用的第一个函数
        # response scrapy下载成功的结果
        if TestspiderSpider.is_first:
            TestspiderSpider.is_first = False
            next_url = TestspiderSpider.start_urls[0] + response.xpath('//div[@id="pagination"]/a/@href').extract()[0]
        else:
            try:
                next_url = TestspiderSpider.start_urls[0] + response.xpath('//div[@id="pagination"]/a/@href').extract()[1]
            except:
                next_url = None

        results = response.xpath('//div[@id="results"]//a/@href').extract()
        # response.xpath 选出的对象是Selector,必须使用extract把Selector的内容提取出

        for url_str in results:
            real_url = "http://example.webscraping.com" + url_str
            # 当scrapy框架检测到函数返回的是Request对象,会自动进行下载
            # callback 回调,Request下载成功后回调的函数,用来返回response结果,名称任意指定
            yield Request(url=real_url, callback=self.parse_countryabc, dont_filter=True)
            # print(real_url)
        if next_url is None:
            print('&&&&  crawl end  &&&&')
        else:
            print('Next url is::::', next_url)    # 为方便看网址
            yield Request(url=next_url, callback=self.parse, dont_filter=True)

    def parse_countryabc(self, response):
        # print(response.body)
        item = ScrapyItemItem()
        item['name'] = response.css('tr#places_country__row td.w2p_fw::text').extract_first()
        item['population'] = response.css('tr#places_population__row td.w2p_fw::text').extract_first()
        yield item

 

 然后我配置了settings文件在末尾只需要加两句代码

SQLITE_FILE = 'example.db'     # 此处是要创建的数据库名.db之前可随意写字符,你喜欢就好

ITEM_PIPELINES = {
   'scrapy_item.pipelines.Sqlite3Pipeline': 300,
}     # 这是框架里pipelines,点之前换成你自己的框架名

下面在pipelines文件添加此代码

import sqlite3     # 导数据库


class Sqlite3Pipeline(object):

    def __init__(self, sqlite_file):
        self.sqlite_file = sqlite_file

    @classmethod     
    def from_crawler(cls, crawler):
        """
        @classmethod
            - 无需实例化
            - 可以调用类属性和类方法
            - 无法取到普通的成员属性和方法
        :param crawler: 
        :return: 
        """
        return cls(
            sqlite_file=crawler.settings.get('SQLITE_FILE'),  
        )        # 从 settings.py 提取

    def open_spider(self, spider):
        self.conn = sqlite3.connect(self.sqlite_file)    # 连接数据库
        self.cur = self.conn.cursor()                    # 添加游标

    def process_item(self, item, spider):
        sql = "CREATE TABLE country( name VARCHAR(32) not null, population varchar(32) not null )"         # 此处为原生SQL语句字段为
        try:
            self.cur.execute(sql)     # 创建country的表
        except:
            pass
        sql_insert = """insert into country values (?,?)"""
        param = (item['name'], item['population'])
        self.cur.execute(sql_insert, param)
        self.conn.commit()   # 保存

        return item

    def close_spider(self, spider):
        self.conn.close()

最后就是在items文件加代码了

就加两行代码name和population

import scrapy


class ScrapyItemItem(scrapy.Item):
    # define the fields for your item here like:
    name = scrapy.Field()
    population = scrapy.Field(

执行命令 scrapy crawl TestSpider

就会出现 example.db 的数据库进入里面就可以看见数据了

快乐人生,笑对未来,也许你有更好的代码和想法,不如我们交个朋友相互探索,说不准有小奇迹出现,O(∩_∩)O嘻嘻~

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值