用scrapy爬取讀遠(yuǎn)網(wǎng)站書籍信息

這里是spiders


Paste_Image.png
# -*- coding: utf-8 -*-
import scrapy
from scrapy_redis.spiders import RedisSpider
from Program.items import ProgramItem

class ReadcolorSpider(RedisSpider):
    name = "readcolorredis"
    allowed_domains = ["readcolor.com"]
    redis_key = 'readcolorredis:star_urls'
    start_urls = ['http://readcolor.com/lists']這句話一定要打開,不然就算網(wǎng)址喂給了redis,爬蟲也讀取不了
    url = 'http://readcolor.com'

    def parse(self, response):
        book_list_group = response.xpath('//article[@style="margin:10px 0 20px;"]')
        for book_list in book_list_group:
            item = ProgramItem()
            item['book_list_title'] = book_list.xpath('header/h3/a/text()').extract()[0]
            item['book_number'] = book_list.xpath('p/a/text()').extract()[0]
            book_list_url = book_list.xpath('header/h3/a/@href').extract()[0]
            yield scrapy.Request(self.url + book_list_url, callback=self.parse_book_list_detail, meta={'item': item})這句話,
將找到的每個書單的鏈接調(diào)用下面的函數(shù)王污,提取書單里面的信息

        next_page = response.xpath('//li[@class="next"]/a/@href').extract()
        if next_page:
                yield scrapy.Request(next_page[0], callback=self.parse)讓爬蟲自動爬取下一頁
                
    def parse_book_list_detail(self, response):
        item = response.meta['item']
        summary = response.xpath('//div[@id="list-description"]/p/text()').extract()
        item['book_list_summary'] = '\n'.join(summary)
        #item['book_url']=response.xpath('//div[@id="body"]/div/div[3]/div[1]/ul[2]/li[1]/div/article/h3/a/@href').extract()[0]
        item['book_list_author'] =response.xpath('//div[@id="body"]/div/div[3]/div[1]/article/header/div/div/a/text()').extract()[0]
        item['book_list_date'] = response.xpath('//div[@id="body"]/div/div[3]/div[1]/article/header/div/div/text()').extract()[0]
        #item['book_name']=response.xpath('//div[@id="body"]/div/div[3]/div[1]/ul[2]/li[1]/div/article/h3/a/text()').extract()[0]
        #item['book_author'] =response.xpath('//div[@id="body"]/div/div[3]/div[1]/ul[2]/li[1]/div/article/h3/small/text()').extract()[0]
        #item['book_summary']=response.xpath('//div[@id="body"]/div/div[3]/div[1]/ul[2]/li[1]/div/article/p/text()').extract()[0]
        book_list = response.xpath('//li[@class="lists-book"]/div[@class="media"]/article')
        for book in book_list:
            item_book = item.copy()  # 深度copy,否則后面的結(jié)果會覆蓋前面的結(jié)果。
            item_book['book_name'] = book.xpath('h3/a/text()').extract()[0]
            item_book['book_url'] = book.xpath('h3/a/@href').extract()[0]
            book_author = book.xpath('h3/small/text()').extract()
            item_book['book_author'] = book_author[0] if book_author else 'N/A'  # 由于書的作者和簡介可能為空,因此這里需要做判斷
            book_summary = book.xpath('p/text()').extract()
            item_book['book_summary'] = book_summary[0] if book_summary else 'N/A'

            yield item_book

        yield item


這是pipeline文件的代碼

# -*- 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.conf import settings

class ProgramPipeline(object):
    '''def __init__(self):
        client = pymongo.MongoClient()
        db = client[settings['MONGODB_DBNAME']]
        self.post = db[settings['MONGODB_DOCNAME']]'''




    def __init__(self):
        host=settings['MONGODB_HOST']
        port=settings['MONGODB_PORT']
        db_name = settings['MONGODB_DBNAME']
        client=pymongo.MongoClient(host=host,port=port)鏈接數(shù)據(jù)庫
        db=client[db_name]
        self.post=db[settings['MONGODB_DOCNAME']]
    def process_item(self, item, spider):
        book_info=dict(item)
        self.post.insert(book_info)
        return item

這是setting里面的代碼楚午,存數(shù)據(jù)庫端口一些信息玉掸,以及redis所在的一些信息,因為redis在本機(jī)醒叁,所以
redis的IP就不用寫出來司浪,如果讀取別的電腦的redis上的鏈接,就要寫出來把沼,這是分布式爬蟲的原來
如果是別的

Paste_Image.png
# -*- coding: utf-8 -*-

# Scrapy settings for Program 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 = 'Program'

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


# Crawl responsibly by identifying yourself (and your website) on the user-agent
USER_AGENT = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36'

# Obey robots.txt rules
ROBOTSTXT_OBEY = False

DOWNLOAD_DELAY = 1 #每次請求間隔1秒

# Disable cookies (enabled by default)
COOKIES_ENABLED = False

# Enables scheduling storing requests queue in redis.
SCHEDULER = "scrapy_redis.scheduler.Scheduler"調(diào)度器

# Ensure all spiders share same duplicates filter through redis.
DUPEFILTER_CLASS = "scrapy_redis.dupefilter.RFPDupeFilter"

# Configure item pipelines
# See http://scrapy.readthedocs.org/en/latest/topics/item-pipeline.html
ITEM_PIPELINES = {
    'Program.pipelines.ProgramPipeline': 300,
}

# Don't cleanup redis queues, allows to pause/resume crawls.
SCHEDULER_PERSIST = True

SCHEDULER_QUEUE_CLASS = "scrapy_redis.queue.SpiderPriorityQueue"隊列順序

MONGODB_HOST = '127.0.0.1'
MONGODB_PORT = 27017
MONGODB_DBNAME = 'jikexueyuan'

運(yùn)行結(jié)果

Paste_Image.png
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末啊易,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子饮睬,更是在濱河造成了極大的恐慌租谈,老刑警劉巖,帶你破解...
    沈念sama閱讀 222,183評論 6 516
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件捆愁,死亡現(xiàn)場離奇詭異割去,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)昼丑,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,850評論 3 399
  • 文/潘曉璐 我一進(jìn)店門呻逆,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人菩帝,你說我怎么就攤上這事咖城〔缤龋” “怎么了?”我有些...
    開封第一講書人閱讀 168,766評論 0 361
  • 文/不壞的土叔 我叫張陵宜雀,是天一觀的道長切平。 經(jīng)常有香客問我,道長辐董,這世上最難降的妖魔是什么悴品? 我笑而不...
    開封第一講書人閱讀 59,854評論 1 299
  • 正文 為了忘掉前任,我火速辦了婚禮简烘,結(jié)果婚禮上苔严,老公的妹妹穿的比我還像新娘。我一直安慰自己夸研,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 68,871評論 6 398
  • 文/花漫 我一把揭開白布依鸥。 她就那樣靜靜地躺著亥至,像睡著了一般。 火紅的嫁衣襯著肌膚如雪贱迟。 梳的紋絲不亂的頭發(fā)上姐扮,一...
    開封第一講書人閱讀 52,457評論 1 311
  • 那天匀谣,我揣著相機(jī)與錄音眷柔,去河邊找鬼亚享。 笑死啄枕,一個胖子當(dāng)著我的面吹牛柴罐,可吹牛的內(nèi)容都是我干的绵疲。 我是一名探鬼主播梭姓,決...
    沈念sama閱讀 40,999評論 3 422
  • 文/蒼蘭香墨 我猛地睜開眼仪搔,長吁一口氣:“原來是場噩夢啊……” “哼忧换!你這毒婦竟也來了恬惯?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,914評論 0 277
  • 序言:老撾萬榮一對情侶失蹤亚茬,失蹤者是張志新(化名)和其女友劉穎酪耳,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體刹缝,經(jīng)...
    沈念sama閱讀 46,465評論 1 319
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡碗暗,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,543評論 3 342
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了梢夯。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片言疗。...
    茶點(diǎn)故事閱讀 40,675評論 1 353
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖颂砸,靈堂內(nèi)的尸體忽然破棺而出洲守,到底是詐尸還是另有隱情疑务,我是刑警寧澤,帶...
    沈念sama閱讀 36,354評論 5 351
  • 正文 年R本政府宣布梗醇,位于F島的核電站知允,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏叙谨。R本人自食惡果不足惜温鸽,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 42,029評論 3 335
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望手负。 院中可真熱鬧涤垫,春花似錦、人聲如沸竟终。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,514評論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽统捶。三九已至榆芦,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間喘鸟,已是汗流浹背匆绣。 一陣腳步聲響...
    開封第一講書人閱讀 33,616評論 1 274
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留什黑,地道東北人崎淳。 一個月前我還...
    沈念sama閱讀 49,091評論 3 378
  • 正文 我出身青樓,卻偏偏與公主長得像愕把,于是被迫代替她去往敵國和親拣凹。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,685評論 2 360

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