實(shí)現(xiàn)Pyspider爬蟲結(jié)果的自定義ResultWorker

前言

最近在用pyspider實(shí)現(xiàn)項目的爬蟲系統(tǒng)没佑,鑒于我們需要自定義的爬蟲結(jié)果。所有需要重寫pyspider自身的ResultWorker焚刚。MyResultWorker是對其的on_result(xxx)進(jìn)行的重寫濒蒋。

自定義ResultWoker,重寫on_result方法:

模塊:CustomResultWorker.py

#!/usr/bin/env python
# -*- encoding: utf-8 -*-
# author: hzliwenhao
# Created on 2017-11-12

import mysql.connector
import time
import logging

from mysql.connector import errorcode
from pyspider.result import ResultWorker

logger = logging.getLogger("MyResultWorker")


class MyResultWorker(ResultWorker):
    def on_result(self, task, result):
        """override"""
        # assert task['taskid']
        # assert task['project']
        # assert task['url']
        # assert result
        # 插入結(jié)果楼誓,部分?jǐn)?shù)據(jù)是硬編碼的玉锌,方便測試
        if MySQLDB().insert(app_id=1, instance_name='test_name', url=task['url']):
            logger.info('result %s:%s %s -> %.30r' % (
                task['project'], task['taskid'], task['url'], result))


class MySQLDB:
    username = 'appops'
    password = 'root123'
    database = 'resultdb2'
    host = '127.0.0.1'
    port = 13308

    connection = None
    is_connect = True
    placeholder = '%s'

    def __init__(self):
        """init db"""
        if self.is_connect:
            self.connect()

    @staticmethod
    def escape(string):
        return '`%s`' % string

    def connect(self):
        connect_kvs = {
            'user': self.username,
            'password': self.password,
            'host': self.host,
            'port': self.port,
            'database': self.database
        }

        try:
            cnx = mysql.connector.connect(**connect_kvs)
            self.connection = cnx
            return True
        except mysql.connector.Error as err:
            if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
                print("The credentials you provided are not correct.")
            elif err.errno == errorcode.ER_BAD_DB_ERROR:
                print("The database you provided does not exist.")
            else:
                print("Something went wrong: ", err)
            return False

    def insert(self, **values):
        """insert data"""
        if self.connection is None:
            print("Please connect first")
            return False

        cursor = self.connection.cursor()

        sql = "insert into result_info " \
              "(app_id, instance_name, url, insert_time) " \
              "values " \
              "(%s,%s,%s,%s)"
        # values
        app_id = values['app_id']
        instance_name = values['instance_name']
        url = values['url']
        insert_time = int(round(time.time() * 1000))

        try:
            cursor.execute(sql, (app_id, instance_name, url, insert_time))
            self.connection.commit()
            return True
        except mysql.connector.Error as err:
            print("An error occurred: {}".format(err))
            return False


if __name__ == '__main__':
    import sys

    reload(sys)
    sys.setdefaultencoding('gbk')
    db = MySQLDB()
    db.insert(app_id=123, instance_name='test_name', url='url')

使用方法

方法1 - 命令行指定

pyspider result_worker --result-cls=CustomResultWorker.MyResultWorker // 模塊名.類名

方法2

pyspider -c config.json result_worker

  1. -c config.json 配置文件指定
{
 "taskdb":"mysql+taskdb://appops:root123@localhost:3306/taskdb", // mysql
 "projectdb":"mysql+projectdb://appops:root123@localhost:3306/projectdb", // mysql
 "resultdb":"mysql+resultdb://appops:root123@localhost:3306/resultdb", // mysql
 "message_queue": "redis://localhost:6379/0", // redis
 "webui":{ // 界面賬戶
  "username": "appops",
  "password": "root123",
  "need-auth": true
 },
"scheduler":{
  "delete-time": 3600 // 刪除項目的時間
 },
"result_worker":{
    "result_cls": "CustomResultWorker.MyResultWorker"
 }
}

資料

  1. https://github.com/binux/pyspider (pyspier源碼)
  2. http://docs.pyspider.org/en/latest/Working-with-Results/ (文檔)
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市疟羹,隨后出現(xiàn)的幾起案子主守,更是在濱河造成了極大的恐慌,老刑警劉巖阁猜,帶你破解...
    沈念sama閱讀 219,539評論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件丸逸,死亡現(xiàn)場離奇詭異,居然都是意外死亡剃袍,警方通過查閱死者的電腦和手機(jī)黄刚,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,594評論 3 396
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來民效,“玉大人憔维,你說我怎么就攤上這事∥沸希” “怎么了业扒?”我有些...
    開封第一講書人閱讀 165,871評論 0 356
  • 文/不壞的土叔 我叫張陵,是天一觀的道長舒萎。 經(jīng)常有香客問我程储,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,963評論 1 295
  • 正文 為了忘掉前任章鲤,我火速辦了婚禮摊灭,結(jié)果婚禮上蔬将,老公的妹妹穿的比我還像新娘兜挨。我一直安慰自己徙融,他們只是感情好喇完,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,984評論 6 393
  • 文/花漫 我一把揭開白布滞时。 她就那樣靜靜地躺著泌绣,像睡著了一般汇陆。 火紅的嫁衣襯著肌膚如雪谒出。 梳的紋絲不亂的頭發(fā)上沪哺,一...
    開封第一講書人閱讀 51,763評論 1 307
  • 那天沈自,我揣著相機(jī)與錄音,去河邊找鬼凤粗。 笑死酥泛,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的嫌拣。 我是一名探鬼主播柔袁,決...
    沈念sama閱讀 40,468評論 3 420
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼异逐!你這毒婦竟也來了捶索?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,357評論 0 276
  • 序言:老撾萬榮一對情侶失蹤灰瞻,失蹤者是張志新(化名)和其女友劉穎腥例,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體酝润,經(jīng)...
    沈念sama閱讀 45,850評論 1 317
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡燎竖,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,002評論 3 338
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了要销。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片构回。...
    茶點(diǎn)故事閱讀 40,144評論 1 351
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖疏咐,靈堂內(nèi)的尸體忽然破棺而出纤掸,到底是詐尸還是另有隱情,我是刑警寧澤浑塞,帶...
    沈念sama閱讀 35,823評論 5 346
  • 正文 年R本政府宣布借跪,位于F島的核電站,受9級特大地震影響酌壕,放射性物質(zhì)發(fā)生泄漏掏愁。R本人自食惡果不足惜歇由,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,483評論 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望托猩。 院中可真熱鬧印蓖,春花似錦辽慕、人聲如沸京腥。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,026評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽公浪。三九已至,卻和暖如春船侧,著一層夾襖步出監(jiān)牢的瞬間欠气,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,150評論 1 272
  • 我被黑心中介騙來泰國打工镜撩, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留预柒,地道東北人。 一個月前我還...
    沈念sama閱讀 48,415評論 3 373
  • 正文 我出身青樓袁梗,卻偏偏與公主長得像宜鸯,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子遮怜,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,092評論 2 355

推薦閱讀更多精彩內(nèi)容

  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理淋袖,服務(wù)發(fā)現(xiàn),斷路器锯梁,智...
    卡卡羅2017閱讀 134,672評論 18 139
  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 172,190評論 25 707
  • 轉(zhuǎn)至元數(shù)據(jù)結(jié)尾創(chuàng)建: 董瀟偉即碗,最新修改于: 十二月 23, 2016 轉(zhuǎn)至元數(shù)據(jù)起始第一章:isa和Class一....
    40c0490e5268閱讀 1,721評論 0 9
  • 能救別人的是專業(yè)知識,而能救自己的是精神寄托陌凳,但能將二者入會貫通的其實(shí)也沒幾個人剥懒。安迪算一個吧!
    小秋秋球球閱讀 233評論 0 0
  • 早上在家里擠牙膏刷牙合敦,拿起牙膏初橘,突然發(fā)現(xiàn)牙膏管早就已經(jīng)被擠得變形了。節(jié)前幾天已經(jīng)發(fā)現(xiàn)快用完了蛤肌,但一直沒舍得...
    我要去扭腰閱讀 1,065評論 1 0