毒舌電影社區(qū)爬蟲

上一次寫了scrapy-redis分布式爬蟲的環(huán)境搭建寓涨,現(xiàn)在以毒舌電影社區(qū)為例子編寫毒舌電影社區(qū)的分布式爬蟲例子。如果對于scrapy-redis的環(huán)境搭建不熟悉氯檐,可以直接參考 scrapy-redisf實(shí)現(xiàn)分布式爬蟲戒良;分析毒舌電影社區(qū)需要Fiddler進(jìn)行抓包,這部分可以直接參考 fiddler抓取摩拜單車數(shù)據(jù)包教程冠摄。下面直接給出電影評論接口地址以及參數(shù)糯崎。

  • 1.通過Fiddler抓包分析,可以得到電影評論的接口河泳,以及傳遞的參數(shù)如下沃呢,其中count表示每次調(diào)用接口返回的點(diǎn)評條數(shù),startIndex就是下一條的起始index拆挥,userid是用戶id(如果為0薄霜,代表用戶沒有登錄)
接口地址:
https://dswxapp.dushemovie.com/dsmovieapi/ssl/daily_recmd/list_daily_recmd_dynamic/3
傳遞參數(shù):
{"count":"20","startIndex":"0","userId":"0"}
    1. 毒舌電影社區(qū)基本架構(gòu)圖,數(shù)據(jù)庫Redis維持公共的requestUrl隊(duì)列纸兔,實(shí)現(xiàn)去重和保存爬取到的item惰瓜,MongoDB保存所有的數(shù)據(jù)。Master主機(jī)首先提取url到redis汉矿,slave從中提取url崎坊,并且把爬取到url保存會(huì)redis。Master同樣提取url到redis洲拇,并且從中獲取url進(jìn)行爬取奈揍。


      scrapy-redis架構(gòu)圖
    1. 文件如下:
文件分布
  • 4.爬取邏輯spiders源碼,spider直接繼承scrapy-reids的RedisSpider痹届,保存在Redis數(shù)據(jù)庫的DuzhemovieSpider的starturl中:
  # -*- coding: utf-8 -*-
  import json
  from scrapy import Request
  from time import sleep
  import logging
  from scrapy_redis.spiders import RedisSpider
  class DuzhemovieSpider(RedisSpider):
    name = "duzhemovie"
    # allowed_domains = ["dushemovie.com"]
    # start_urls = ['http://dushemovie.com/']
    redis_key:"DuzhemovieSpider:start_urls" 
    url="https://dswxapp.dushemovie.com/dsmovieapi/ssl/daily_recmd/list_daily_recmd_dynamic/3"
    postBody={"count":"20","startIndex":"0","userId":"0"}
    def start_requests(self):
        yield Request(url=self.url,method="POST",body=str(self.postBody),callback=self.parse)
    def parse(self, response):
        jsonData=json.loads(response.body.decode('UTF-8'))
        yield jsonData
        while True:
            sleep(1)
            self.postBody["startIndex"]=str(int(self.postBody['startIndex'])+20)
            yield Request(url=self.url,method="POST",body=str(self.postBody),callback=self.parse)
  • 5.pipelines保存數(shù)據(jù)item在遠(yuǎn)程阿里云自建數(shù)據(jù)庫MongoDB上,因?yàn)閿?shù)據(jù)都是json格式打月,所以item模塊沒有定義字段值队腐,直接把json格式數(shù)據(jù)寫進(jìn)MongoDB數(shù)據(jù)庫里面。源碼如下:
# -*- coding: utf-8 -*-

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html


import pymongo
from scrapy.exceptions import DropItem
class MongoPipeline(object):
    collection_name="users"
    def __init__(self,mongo_uri,mongo_db,mongo_user,mongo_pass):
        self.mongo_uri=mongo_uri
        self.mongo_db=mongo_db
        self.mongo_user=mongo_user
        self.mongo_pass=mongo_pass
    @classmethod
    def from_crawler(cls,crawler):
        return cls(mongo_uri=crawler.settings.get('MONGO_URI'),mongo_db=crawler.settings.get('MONGO_DATABASE'),mongo_user=crawler.settings.get("MONGO_USER"),mongo_pass=crawler.settings.get("MONGO_PASS"))
    def open_spider(self, spider):
        self.client = pymongo.MongoClient(self.mongo_uri)
        self.db = self.client[self.mongo_db]
        self.db.authenticate(self.mongo_user,self.mongo_pass)
        
    def close_spider(self, spider):
        self.client.close()

    def process_item(self, item, spider):
        # self.db[self.collection_name].update({'url_token': item['url_token']}, {'$set': dict(item)}, True)
        # return item
        if item["dynamicDataList"]==None:
            raise DropItem("Data is None")
        else:
            self.db[self.collection_name].insert(dict(item))
            return item
  • 6.項(xiàng)目設(shè)置模塊奏篙,主要設(shè)置MongoDB的地址柴淘,用戶,密碼以及Redis數(shù)據(jù)庫的用戶名與密碼秘通,以及常見的一些scrapy控制爬取速率和item为严,middleWare順序。
 lines (94 sloc)  4 KB
# -*- coding: utf-8 -*-

# Scrapy settings for dushe project
#
# For simplicity, this file contains only settings considered important or
# commonly used. You can find more settings consulting the documentation:
#
#     http://doc.scrapy.org/en/latest/topics/settings.html
#     http://scrapy.readthedocs.org/en/latest/topics/downloader-middleware.html
#     http://scrapy.readthedocs.org/en/latest/topics/spider-middleware.html

BOT_NAME = 'dushe'

SPIDER_MODULES = ['dushe.spiders']
NEWSPIDER_MODULE = 'dushe.spiders'


# Crawl responsibly by identifying yourself (and your website) on the user-agent
#USER_AGENT = 'dushe (+http://www.yourdomain.com)'

# Obey robots.txt rules
ROBOTSTXT_OBEY = False

# Configure maximum concurrent requests performed by Scrapy (default: 16)
#CONCURRENT_REQUESTS = 32

# Configure a delay for requests for the same website (default: 0)
# See http://scrapy.readthedocs.org/en/latest/topics/settings.html#download-delay
# See also autothrottle settings and docs
#DOWNLOAD_DELAY = 3
# The download delay setting will honor only one of:
#CONCURRENT_REQUESTS_PER_DOMAIN = 16
#CONCURRENT_REQUESTS_PER_IP = 16

# Disable cookies (enabled by default)
#COOKIES_ENABLED = False

# Disable Telnet Console (enabled by default)
#TELNETCONSOLE_ENABLED = False

# Override the default request headers:
DEFAULT_REQUEST_HEADERS = {
    'Host': 'dswxapp.dushemovie.com',
    'Content-Type': 'application/json',
    'Accept-Language':' zh-cn',
    'Accept-Encoding': 'gzip, deflate',
    'Connection':' keep-alive',
    'Accept': '*/*',
    'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 10_0_1 like Mac OS X) AppleWebKit/602.1.50 (KHTML, like Gecko) Mobile/14A403 MicroMessenger/6.5.16 NetType/WIFI Language/zh_CN',
    'Referer': 'https://servicewechat.com/wxae1df0a33ef19e00/18/page-frame.html',
    'acw_tc':'AQAAAGEFNWv+5AsARUVJ3wWxzmZzc+SK; Path=/; HttpOnly',
    'Expires': 'Thu, 01 Jan 1970 00:00:00 GMT',
    'di': {"uid":0,"sysType":1,"versionCode":1,"channelCode":"WeChat Small App","lang":"zh_CN","local":"CN","sign":"null"}
}

# Enable or disable spider middlewares
# See http://scrapy.readthedocs.org/en/latest/topics/spider-middleware.html
#SPIDER_MIDDLEWARES = {
#    'dushe.middlewares.DusheSpiderMiddleware': 543,
#}

# Enable or disable downloader middlewares
# See http://scrapy.readthedocs.org/en/latest/topics/downloader-middleware.html
#DOWNLOADER_MIDDLEWARES = {
#    'dushe.middlewares.MyCustomDownloaderMiddleware': 543,
#}

# Enable or disable extensions
# See http://scrapy.readthedocs.org/en/latest/topics/extensions.html
#EXTENSIONS = {
#    'scrapy.extensions.telnet.TelnetConsole': None,
#}

# Configure item pipelines
# See http://scrapy.readthedocs.org/en/latest/topics/item-pipeline.html
ITEM_PIPELINES = {
   'dushe.pipelines.MongoPipeline': 300,
   'scrapy_redis.pipelines.RedisPipeline': 301
}

# Enable and configure the AutoThrottle extension (disabled by default)
# See http://doc.scrapy.org/en/latest/topics/autothrottle.html
#AUTOTHROTTLE_ENABLED = True
# The initial download delay
#AUTOTHROTTLE_START_DELAY = 5
# The maximum download delay to be set in case of high latencies
#AUTOTHROTTLE_MAX_DELAY = 60
# The average number of requests Scrapy should be sending in parallel to
# each remote server
#AUTOTHROTTLE_TARGET_CONCURRENCY = 1.0
# Enable showing throttling stats for every response received:
#AUTOTHROTTLE_DEBUG = False

# Enable and configure HTTP caching (disabled by default)
# See http://scrapy.readthedocs.org/en/latest/topics/downloader-middleware.html#httpcache-middleware-settings
#HTTPCACHE_ENABLED = True
#HTTPCACHE_EXPIRATION_SECS = 0
#HTTPCACHE_DIR = 'httpcache'
#HTTPCACHE_IGNORE_HTTP_CODES = []
#HTTPCACHE_STORAGE = 'scrapy.extensions.httpcache.FilesystemCacheStorage'
HTTPERROR_ALLOWED_CODES = [404]
DOWNLOAD_DELAY = 3
MONGO_URI="remoteAddress"
MONGO_DATABASE='databaseName'
MONGO_USER="username"
MONGO_PASS="password"
SCHEDULER = "scrapy_redis.scheduler.Scheduler"
DUPEFILTER_CLASS = "scrapy_redis.dupefilter.RFPDupeFilter"
REDIS_URL = 'redis://username:password@remoteAddress:port'
SCHEDULER_IDLE_BEFORE_CLOSE = 10
SCHEDULER_PERSIST=False
  • 爬取的數(shù)據(jù)展示如下:


    數(shù)據(jù)庫展示

github地址:https://github.com/laternkiwis/duSheCommunity

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末肺稀,一起剝皮案震驚了整個(gè)濱河市第股,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌话原,老刑警劉巖夕吻,帶你破解...
    沈念sama閱讀 219,589評論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異繁仁,居然都是意外死亡涉馅,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,615評論 3 396
  • 文/潘曉璐 我一進(jìn)店門黄虱,熙熙樓的掌柜王于貴愁眉苦臉地迎上來稚矿,“玉大人,你說我怎么就攤上這事捻浦∥畲В” “怎么了?”我有些...
    開封第一講書人閱讀 165,933評論 0 356
  • 文/不壞的土叔 我叫張陵朱灿,是天一觀的道長昧识。 經(jīng)常有香客問我,道長母剥,這世上最難降的妖魔是什么滞诺? 我笑而不...
    開封第一講書人閱讀 58,976評論 1 295
  • 正文 為了忘掉前任,我火速辦了婚禮环疼,結(jié)果婚禮上习霹,老公的妹妹穿的比我還像新娘。我一直安慰自己炫隶,他們只是感情好淋叶,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,999評論 6 393
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著伪阶,像睡著了一般煞檩。 火紅的嫁衣襯著肌膚如雪处嫌。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,775評論 1 307
  • 那天斟湃,我揣著相機(jī)與錄音熏迹,去河邊找鬼。 笑死凝赛,一個(gè)胖子當(dāng)著我的面吹牛注暗,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播墓猎,決...
    沈念sama閱讀 40,474評論 3 420
  • 文/蒼蘭香墨 我猛地睜開眼捆昏,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了毙沾?” 一聲冷哼從身側(cè)響起骗卜,我...
    開封第一講書人閱讀 39,359評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎左胞,沒想到半個(gè)月后寇仓,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,854評論 1 317
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡罩句,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,007評論 3 338
  • 正文 我和宋清朗相戀三年焚刺,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了敛摘。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片门烂。...
    茶點(diǎn)故事閱讀 40,146評論 1 351
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖兄淫,靈堂內(nèi)的尸體忽然破棺而出屯远,到底是詐尸還是另有隱情,我是刑警寧澤捕虽,帶...
    沈念sama閱讀 35,826評論 5 346
  • 正文 年R本政府宣布慨丐,位于F島的核電站,受9級特大地震影響泄私,放射性物質(zhì)發(fā)生泄漏房揭。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,484評論 3 331
  • 文/蒙蒙 一晌端、第九天 我趴在偏房一處隱蔽的房頂上張望捅暴。 院中可真熱鬧,春花似錦咧纠、人聲如沸蓬痒。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,029評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽梧奢。三九已至狱掂,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間亲轨,已是汗流浹背趋惨。 一陣腳步聲響...
    開封第一講書人閱讀 33,153評論 1 272
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留惦蚊,地道東北人希柿。 一個(gè)月前我還...
    沈念sama閱讀 48,420評論 3 373
  • 正文 我出身青樓,卻偏偏與公主長得像养筒,于是被迫代替她去往敵國和親曾撤。 傳聞我的和親對象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,107評論 2 356

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