本來今天要繼續更新 scrapy爬取美女圖片 系列文章,可是發現使用免費的代理ip都非常不穩定,有時候連接上,有時候連接不上,所以我想找到穩定的代理ip,下次再更新 scrapy爬取美女圖片之應對反爬蟲 文章。(我的新書《Python爬蟲開發與項目實戰》出版了,大家可以看一下樣章)
好了,廢話不多說,咱們進入今天的主題。這一篇文章是關於爬取盜墓筆記,主要技術要點是scrapy的使用,scrapy框架中使用mongodb數據庫,文件的保存。

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

按照咱們之前的學習爬蟲的做法,使用firebug審查元素,查看如何解析html。
這次咱們要把書的名稱,章節,章節名稱,章節鏈接抽取出來,存儲到數據庫中,同時將文章的內容提取出來存成txt文件。

看一下html結構就會發現這個頁面結構非常分明,標題的html節點是 div class = ''mulu-title",章節的節點是 div class= "box" ,每一章的節點是 div class= "box"中的<li>標簽。
然后咱們將第一章的鏈接 http://seputu.com/biji1/1.html打開,上面就是文章的內容。

可以看到文章的內容是使用 div class ="content-body"中的<p>標簽包裹起來的,總體來說提取難度挺小。
打開cmd,輸入scrapy startproject daomubiji,這時候會生成一個工程,然后我把整個工程復制到pycharm中

上圖就是工程的結構。
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/
