[Sasila] 一个简单易用的爬虫框架

2017-07-12 14:01:31 +08:00
 darksand

现在有很多爬虫框架,比如scrapywebmagicpyspider都可以在爬虫工作中使用,也可以直接通过requests+beautifulsoup来写一些个性化的小型爬虫脚本。但是在实际爬取过程当中,爬虫框架各自有优势和缺陷。比如 scrapy,它的功能强大,但过于强大的功能也许反而让新手无所适从,并且它采用 twisted 异步框架开发,对新手来说源码难以理解,项目难于调试。所以我模仿这些爬虫框架的优势,以尽量简单的原则,搭配 gevent(实际上是 grequests)开发了这套轻量级爬虫框架。

主要特点

安装

pip install sasila

准备

REDIS_HOST = 'localhost'
REDIS_PORT = 6379

构建 processor(解析器)

#!/usr/bin/env python
# -*- coding: utf-8 -*-
from bs4 import BeautifulSoup as bs
from sasila.system_normal.processor.base_processor import BaseProcessor
from sasila.system_normal.downloader.http.spider_request import Request
from sasila.system_normal.spider.spider_core import SpiderCore

class Mzi_Processor(BaseProcessor):
    spider_id = 'mzi_spider'
    spider_name = 'mzi_spider'
    allowed_domains = ['mzitu.com']
    start_requests = [Request(url='http://www.mzitu.com/', priority=0)]

    @checkResponse
    def process(self, response):
        soup = bs(response.m_response.content, 'lxml')
        print soup.title.string
        href_list = soup.select('a')
        for href in href_list:
            yield Request(url=response.nice_join(href['href']))

写法与 scrapy 几乎一样

与 scrapy 相似,sasila 同样提供LinkExtractor 的方式来提取链接,以下是用LinkExtractor的方式构造processor下载妹子图的示例

#!/usr/bin/env python
# -*- coding: utf-8 -*-
from sasila.system_normal.processor.base_processor import BaseProcessor, Rule, LinkExtractor
from sasila.system_normal.downloader.http.spider_request import Request
import os
import uuid

class MezituProcessor(BaseProcessor):
    spider_id = 'mzitu'
    spider_name = 'mzitu'
    allowed_domains = ['mzitu.com', 'meizitu.net']
    start_requests = [Request(url='http://www.mzitu.com/xinggan/')]

    rules = (
        Rule(LinkExtractor(regex_str=r"http://i.meizitu.net/\d{4}/\d{2}/[0-9a-z]+.jpg"),callback="save", priority=3),
        Rule(LinkExtractor(regex_str=r"http://www.mzitu.com/\d+"), priority=1),
        Rule(LinkExtractor(regex_str=r"http://www.mzitu.com/\d+/\d+"), priority=2),
        Rule(LinkExtractor(regex_str=r"http://www.mzitu.com/xinggan/page/\d+"), priority=0),
    )

    def save(self, response):
        if response.m_response:
            if not os.path.exists("img"):
                os.mkdir("img")
            with open("img/" + str(uuid.uuid1()) + ".jpg", 'wb') as fs:
                fs.write(response.m_response.content)
                print("download success!")

LinkExtractor 的构造方式为

LinkExtractor(regex_str=None, css_str=None, process_value=None)

构建 pipeline

该 pipeline 获取数据后将数据转为 json 格式,并输出到屏幕

from sasila.system_normal.pipeline.base_pipeline import ItemPipeline
import json

class ConsolePipeline(ItemPipeline):
    def process_item(self, item):
        print json.dumps(item).decode("unicode-escape")

构建 spider(爬虫对象)

from sasila.system_normal.spider.spider_core import SpiderCore

spider = SpiderCore(Mzi_Processor())
SpiderCore(processor=None, downloader=None, use_proxy=False,scheduler=None,batch_size=None,time_sleep=None)
PROXY_PATH_REQUEST = 'proxy/path'
127.0.0.1,8080
127.0.0.2,8080,user,pwd
127.0.0.3,8080,user,pwd
 spider = spider.set_pipeline(ConsolePipeline())
spider.start()
from sasila.system_normal.manager import manager
from sasila import system_web

manager.set_spider(spider)

system_web.start()

访问 http://127.0.0.1:5000/slow_spider/start?spider_id=mzi_spider 来启动爬虫。 访问 http://127.0.0.1:5000/slow_spider/stop?spider_id=mzi_spider 来停止爬虫。 访问 http://127.0.0.1:5000/slow_spider/detail?spider_id=mzi_spider 来查看爬虫详细信息。

针对需要登录才能爬取的处理办法

架构

即时爬虫

即时爬虫是可以通过 api 调用,传入需要爬取的页面或者需求,即时爬取数据并返回结果。现阶段开发并不完善。仅提供思路参考。示例核心代码在 sasila.system_instant 中。

为啥叫 Sasila ?

作为一个 wower,你可以猜到吗ヾ( ̄▽ ̄)

环境

暂时只支持 python2.7,其它版本还没有测试过。。

联系方式

如果对使用有疑问,或者有想法,欢迎加入讨论群:602909155 交流~

项目地址

3221 次点击
所在节点    Python
7 条回复
NaVient
2017-07-12 14:24:54 +08:00
支持,已 star
ikeeper
2017-07-12 17:22:46 +08:00
支持,已 star
tedchen
2017-07-12 19:48:24 +08:00
支持,已 star
cxd44
2017-07-12 20:39:06 +08:00
支持
darksand
2017-07-12 22:57:18 +08:00
@cxd44 谢谢!
darksand
2017-07-12 22:57:48 +08:00
@tedchen 谢谢!
yangyaofei
2017-07-13 16:25:37 +08:00
正在用 pyspider 做项目,不知道这个和 pyspider 比起来优势是啥?

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/374777

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX