工具環(huán)境
語言:python3.6
數(shù)據(jù)庫:MongoDB (安裝及運行命令如下)
python3-m pip install pymongobrew install mongodbmongod--config/usr/local/etc/mongod.conf
框架:scrapy1.5.1 (安裝命令如下)
python3-m pip install Scrapy
用 scrapy 框架創(chuàng)建一個爬蟲項目
在終端執(zhí)行如下命令,創(chuàng)建一個名為 myspider 的爬蟲項目
scrapy startproject myspider
即可得到一個如下結(jié)構(gòu)的文件目錄

創(chuàng)建 crawl 樣式的爬蟲
針對不同的用途, scrapy 提供了不同種類的爬蟲類型,分別是
Spider:所有爬蟲的祖宗
CrawlSpider:比較常用的爬取整站數(shù)據(jù)的爬蟲(下面的例子就是用這種)
XMLFeedSpider
CSVFeedSpider
SitemapSpider
先在命令行進入到 spiders 目錄下
cd myspider/myspider/spiders
然后創(chuàng)建 crawl 類型的爬蟲模板
scrapy genspider-t crawl zgmlxc www.zgmlxc.com.cn
參數(shù)說明:
-t crawl?指明爬蟲的類型
zgmlxc?是我給這個爬蟲取的名字
www.zgmlxc.com.cn?是我要爬取的站點
完善小爬蟲 zgmlxc
打開?zgmlxc.py?文件,可以看到一個基本的爬蟲模板,現(xiàn)在就開始對其進行一系列的配置工作,讓這個小爬蟲根據(jù)我的指令去爬取信息。
配置跟蹤頁面規(guī)則
rules=(//定位到 www.zgmlxc.com.cn/node/72.jspx 這個頁面? ? Rule(LinkExtractor(allow=r'.72\.jspx')),//在上面規(guī)定的頁面中,尋找符合下面規(guī)則的 url,爬取里面的內(nèi)容,并把獲取的信息返回給 parse_item()函數(shù)? ? Rule(LinkExtractor(allow=r'./info/\d+\.jspx'),callback='parse_item'),)
這里有個小坑,就是最后一個 Rule 后面必須有逗號,否則報錯,哈哈哈
rules=(Rule(LinkExtractor(allow=r'./info/\d+\.jspx'),callback='parse_item',follow=True),)
在 items.py 內(nèi)定義我們需要提取的字段
importscrapyclassCrawlspiderItem(scrapy.Item):# define the fields for your item here like:# name = scrapy.Field()title=scrapy.Field()content=scrapy.Field()piclist=scrapy.Field()shortname=scrapy.Field()
完善 parse_item 函數(shù)
這里就是把上一步返回的內(nèi)容,配置規(guī)則,提取我們想要的信息。這里必須用?join?方法,是為了方便后面順利導入數(shù)據(jù)庫。
defparse_item(self,response):yield{'title':' '.join(response.xpath("http://div[@class='head']/h3/text()").get()).strip(),'shortname':' '.join(response.xpath("http://div[@class='body']/p/strong/text()").get()).strip(),'piclist':' '.join(response.xpath("http://div[@class='body']/p/img/@src").getall()).strip(),'content':' '.join(response.css("div.body").extract()).strip(),}
PS: 下面是提取內(nèi)容的常用規(guī)則,直接總結(jié)在這里了:
1). 獲取 img 標簽中的 src:
//img[@class='photo-large']/@src
2). 獲取文章主題內(nèi)容及排版:
response.css("div.body").extract()
將信息存入 MogoDB 數(shù)據(jù)庫
設置數(shù)據(jù)庫信息
打開?settings.py?添加如下信息:
# 建立爬蟲與數(shù)據(jù)庫之間的連接關系ITEM_PIPELINES={'crawlspider.pipelines.MongoDBPipeline':300,}# 設置數(shù)據(jù)庫信息MONGODB_SERVER="localhost"MONGODB_PORT=27017MONGODB_DB='spider_world'MONGODB_COLLECTION='zgmlxc'# 設置文明爬蟲, 意思是每個請求之間間歇 5 秒, 對站點友好, 也防止被黑名單```pyDOWNLOAD_DELAY=5
在?piplines.py?中
importpymongofromscrapy.confimportsettingsfromscrapy.exceptionsimportDropItemfromscrapyimportlogclassMongoDBPipeline(object):def__init__(self):connection=pymongo.MongoClient(settings['MONGODB_SERVER'],settings['MONGODB_PORT'])db=connection[settings['MONGODB_DB']]self.collection=db[settings['MONGODB_COLLECTION']]defprocess_item(self,item,spider):valid=Truefordatainitem:ifnotdata:valid=FalseraiseDropItem("Missing {0}!".format(data))ifvalid:self.collection.insert(dict(item))log.msg("Question added to MongoDB database!",level=log.DEBUG,spider=spider)returnitem
在終端運行這個小爬蟲
scrapy crawl myspider
在 navicat 中查看信息入庫情況
如下圖新建一個 MogoDB 的數(shù)據(jù)庫連接,填入上面配置的信息,如果一切順利, 就可以看到我們想要的信息都已經(jīng)入庫了。

以上就完成了自定義爬蟲到數(shù)據(jù)入庫的全過程
更多技術素材視頻可加交流群下載:1029344413