python爬蟲-爬取盜墓筆記

  原本今天要繼續更新 scrapy爬取美女圖片 系列文章,但是發現使用免費的代理ip都很是不穩定,有時候鏈接上,有時候鏈接不上,因此我想找到穩定的代理ip,下次再更新  scrapy爬取美女圖片之應對反爬蟲  文章。(個人新書《Python爬蟲開發與項目實戰》出版了,你們能夠看一下樣章html

      好了,廢話很少說,我們進入今天的主題。這一篇文章是關於爬取盜墓筆記,主要技術要點是scrapy的使用,scrapy框架中使用mongodb數據庫文件的保存python

 

 

 

   此次爬取的網址是  http://seputu.com/。以前也常常在上面在線看盜墓筆記。git

 

 

 

    按照我們以前的學習爬蟲的作法,使用firebug審查元素,查看如何解析html。github

 

       此次我們要把書的名稱,章節,章節名稱,章節連接抽取出來,存儲到數據庫中,同時將文章的內容提取出來存成txt文件mongodb

 

 

 

   看一下html結構就會發現這個頁面結構很是分明,標題的html節點是  div class = ''mulu-title",章節的節點是 div class= "box" ,每一章的節點是 div class= "box"中的<li>標籤數據庫

 

 

 

        而後我們將第一章的連接 http://seputu.com/biji1/1.html打開,上面就是文章的內容。框架

 

 

 

   能夠看到文章的內容是使用 div class ="content-body"中的<p>標籤包裹起來的,整體來講提取難度挺小。dom

 

 

        打開cmd,輸入scrapy startproject daomubiji,這時候會生成一個工程,而後我把整個工程複製到pycharm中scrapy

 

 

  

上圖就是工程的結構。ide

 

        DaomubijiSpider.py ------Spider 蜘蛛

 

        items.py -----------------對要爬取數據的模型定義

 

        pipelines.py-------------處理要存儲的數據(存到數據庫和寫到文件)

 

        settings.py----------------對Scrapy的配置

 

        main.py -------------------啓動爬蟲

 

        test.py -------------------- 測試程序(不參與總體運行)

 

 

   下面將解析和存儲的代碼貼一下,完整代碼已上傳到github:https://github.com/qiyeboy/daomuSpider

 

DaomubijiSpider.py (解析html)
#coding:utf-8
import scrapy
from scrapy.selector import Selector
from daomubiji.items import DaomubijiItem


class daomuSpider(scrapy.Spider):
    name = "daomu"
    allowed_domains = ["seputu.com"]
    start_urls = ["http://seputu.com/"]
    ''.split()

    def parse(self, response):
        selector = Selector(response)
        mulus= selector.xpath("//div[@class='mulu']/div[@class='mulu-title']/center/h2/text()").extract()#將目錄提取出來
        boxs = selector.xpath("//div[@class='mulu']/div[@class='box']")#.extract()
        for i in range(len(mulus)):
            mulu = mulus[i]#提取出來一個目錄
            box = boxs[i]#提取出來一個box
            texts = box.xpath(".//ul/li/a/text()").extract()#將文本提取出來
            urls  = box.xpath(".//ul/li/a/@href").extract()#將連接提取出來
            for j in range(len(urls)):
                item = DaomubijiItem()
                item['bookName'] = mulu
                try:
                    item['bookTitle'] = texts[j].split(' ')[0]
                    item['chapterNum'] = texts[j].split(' ')[1]
                    item['chapterName'] = texts[j].split(' ')[2]
                    item['chapterUrl'] = urls[j]
                    request = scrapy.Request(urls[j],callback=self.parseBody)
                    request.meta['item'] = item
                    yield request


                except Exception,e:
                    print 'excepiton',e
                    continue



    def parseBody(self,response):
        '''
        解析小說章節中的內容
        :param response:
        :return:
        '''
        item = response.meta['item']
        selector = Selector(response)

        item['chapterContent'] ='\r\n'.join(selector.xpath("//div[@class='content-body']/p/text()").extract())
        yield item

  

 

   pipelines.py:(處理要存儲的數據)

# -*- 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 os
from scrapy.pipelines.files import FilesPipeline
from daomubiji import settings
from pymongo import MongoClient

class DaomubijiPipeline(object):
    def process_item(self, item, spider):#將小說進行存儲
        dir_path = '%s/%s/%s'%(settings.FILE_STORE,spider.name,item['bookName']+'_'+item['bookTitle'])#存儲路徑
        print 'dir_path',dir_path
        if not os.path.exists(dir_path):
            os.makedirs(dir_path)
        file_path = '%s/%s'%(dir_path,item['chapterNum']+'_'+item['chapterName']+'.txt')
        with open(file_path,'w') as file_writer:
            file_writer.write(item['chapterContent'].encode('utf-8'))
            file_writer.write('\r\n'.encode('utf-8'))

        file_writer.close()
        return item

class DaomuSqlPipeline(object):

    def __init__(self):
    #鏈接mongo數據庫,並把數據存儲
        client = MongoClient()#'mongodb://localhost:27017/'///'localhost', 27017///'mongodb://tanteng:123456@localhost:27017/'
        db = client.daomu
        self.books = db.books

    def process_item(self, item, spider):
        print 'spider_name',spider.name
        temp ={'bookName':item['bookName'],
               'bookTitle':item['bookTitle'],
               'chapterNum':item['chapterNum'],
               'chapterName':item['chapterName'],
               'chapterUrl':item['chapterUrl']
               }
        self.books.insert(temp)

        return item

  

 

 

      接下來切換到main.py所在目錄,運行python main.py啓動爬蟲。

 

 

         沒過幾分鐘,爬蟲就結束了,我們看一下爬取的數據和文件

 

    

 

         數據庫數據:

 

  

 

  今天的分享就到這裏,若是你們以爲還能夠呀,記得推薦呦。

 

 歡迎你們支持我公衆號:    

 

 

本文章屬於原創做品,歡迎你們轉載分享。尊重原創,轉載請註明來自:七夜的故事 http://www.cnblogs.com/qiyeboy/

相關文章
相關標籤/搜索