本來今天要繼續(xù)更新 **scrapy爬取美女圖片 **系列文章惯殊,可是發(fā)現(xiàn) **使用免費的代理ip都非常不穩(wěn)定,有時候連接上,有時候連接不上 **馒疹,所以我想找到 **穩(wěn)定的代理i p谬泌,下次再更新 scrapy爬取美女圖片之應對反爬蟲 ** 文章滔韵。(我的新書《Python爬蟲開發(fā)與項目實戰(zhàn)》發(fā)布了,大家在這里可以看到樣章)
好了掌实,廢話不多說陪蜻,咱們進入今天的主題。這一篇文章是關于爬取盜墓筆記贱鼻,主要技術要點是 **scrapy的使用 **宴卖,scrapy框架中 **使用mongodb數(shù)據(jù)庫 **, 文件的保存 邻悬。
<p>
<p>
<p>
<p>
這次爬取的網(wǎng)址是 seputu.com症昏。之前也經(jīng)常在上面在線看盜墓筆記。
按照咱們之前的學習爬蟲的做法父丰,使用firebug審查元素肝谭,查看如何解析html。
<p>
這次咱們要把書的名稱,章節(jié)攘烛,章節(jié)名稱魏滚,章節(jié)鏈接抽取出來,存儲到數(shù)據(jù)庫中坟漱,同時將文章的內(nèi)容提取出來存成txt文件鼠次。
<p>
<p>
看一下html結構就會發(fā)現(xiàn)這個頁面結構非常分明,標題的html節(jié)點是 ** div class = ''mulu-title"芋齿,章節(jié)的節(jié)點是 div class= "box" **腥寇,每一章的節(jié)點是 div class= "box"中的li標簽。
<p>
然后咱們將第一章的鏈接 http://seputu.com/biji1/1.html打開沟突,上面就是文章的內(nèi)容花颗。
<p>
<p>
可以看到文章的內(nèi)容是使用 **div class ="content-body"中的p標簽 **包裹起來的,總體來說提取難度挺小惠拭。
打開cmd扩劝,輸入 **scrapy startproject daomubiji **,這時候會生成一個工程,然后我把整個工程復制到 **pycharm **中
**上圖就是工程的結構 **职辅。
DaomubijiSpider.py ------Spider 蜘蛛
items.py -----------------對要爬取數(shù)據(jù)的模型定義
pipelines.py-------------處理要存儲的數(shù)據(jù)(存到數(shù)據(jù)庫和寫到文件)
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("http://div[@class='mulu']/div[@class='mulu-title']/center/h2/text()").extract()#將目錄提取出來
boxs = selector.xpath("http://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):
'''
解析小說章節(jié)中的內(nèi)容
:param response:
:return:
'''
item = response.meta['item']
selector = Selector(response)
item['chapterContent'] ='\r\n'.join(selector.xpath("http://div[@class='content-body']/p/text()").extract())
yield item
pipelines.py:(處理要存儲的數(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 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數(shù)據(jù)庫,并把數(shù)據(jù)存儲
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啟動爬蟲簇秒。
沒過幾分鐘,爬蟲就結束了秀鞭,咱們看一下爬取的數(shù)據(jù)和文件趋观。
數(shù)據(jù)庫數(shù)據(jù):
今天的分享就到這里,如果大家覺得還可以呀锋边,記得打賞呦