Scrapy和MongoDB的應用---爬取

  Scrapy是Python開發的一個快速、高層次的屏幕抓取和web抓取框架,用於抓取Web站點並從頁面中提取結構化的數據.它最吸引人的地方在於任何人均可以根據需求方便的修改。
  MongoDB是現下很是流行的開源的非關係型數據庫(NoSql),它是以「key-value」的形式存儲數據的,在大數據量、高併發、弱事務方面都有很大的優點。
  當Scrapy與MongoDB二者相碰撞會產生怎樣的火花呢?與MongoDB二者相碰撞會產生怎樣的火花呢?如今讓咱們作一個簡單的爬取小說的TEST

   1.安裝Scrapy
        pip install scrapy

   2.下載安裝MongoDB和MongoVUE可視化
        [MongoDB下載地址](https://www.mongodb.org/)
        下載安裝的步驟略過,在bin目錄下建立一個data文件夾用來存放數據的。vue


        [MongoVUE下載地址](http://www.mongovue.com/)web

   安裝完成後咱們須要建立一個數據庫。redis

  

   3.建立一個Scrapy項目
        scrapy startproject novelspider
    目錄結構:其中的novspider.py是須要咱們手動建立的(contrloDB不須要理會)mongodb

  

  4.編寫代碼數據庫

    目標網站:http://www.daomubiji.com/併發

    

  settings.py框架

BOT_NAME = 'novelspider'

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

ITEM_PIPELINES = ['novelspider.pipelines.NovelspiderPipeline']  #導入pipelines.py中的方法

USER_AGENT = 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:39.0) Gecko/20100101 Firefox/39.0'
COOKIES_ENABLED = True

MONGODB_HOST = '127.0.0.1'   
MONGODB_PORT = 27017
MONGODB_DBNAME = 'zzl'    #數據庫名
MONGODB_DOCNAME = 'Book'   #表名

  pipelines.pyscrapy

from scrapy.conf import settings
import pymongo

class NovelspiderPipeline(object):
    def __init__(self):
        host = settings['MONGODB_HOST']
        port = settings['MONGODB_PORT']
        dbName = settings['MONGODB_DBNAME']
        client = pymongo.MongoClient(host=host, port=port)
        tdb = client[dbName]
        self.post = tdb[settings['MONGODB_DOCNAME']]

    def process_item(self, item, spider):
        bookInfo = dict(item)
        self.post.insert(bookInfo)
        return item

  items.pyide

from scrapy import Item,Field


class NovelspiderItem(Item):
    # define the fields for your item here like:
    # name = scrapy.Field()
    bookName = Field()
    bookTitle = Field()
    chapterNum = Field()
    chapterName = Field()
    chapterURL = Field()

  在spiders目錄下建立novspider.py高併發

from scrapy.spiders import CrawlSpider
from scrapy.selector import Selector
from novelspider.items import NovelspiderItem

class novSpider(CrawlSpider):
    name = "novspider"
    redis_key = 'novspider:start_urls'
    start_urls = ['http://www.daomubiji.com/']

    def parse(self,response):
        selector = Selector(response)
        table = selector.xpath('//table')
        for each in table:
            bookName = each.xpath('tr/td[@colspan="3"]/center/h2/text()').extract()[0]
            content = each.xpath('tr/td/a/text()').extract()
            url = each.xpath('tr/td/a/@href').extract()
            for i in range(len(url)):
                item = NovelspiderItem()
                item['bookName'] = bookName
                item['chapterURL'] = url[i]
                try:
                    item['bookTitle'] = content[i].split(' ')[0]
                    item['chapterNum'] = content[i].split(' ')[1]
                except Exception,e:
                    continue

                try:
                    item['chapterName'] = content[i].split(' ')[2]
                except Exception,e:
                    item['chapterName'] = content[i].split(' ')[1][-3:]
                yield item

  5.啓動項目命令: scrapy crawl novspider.  

     抓取結果

  

相關文章
相關標籤/搜索