1 安裝Scrapy
Scrapy是一個(gè)為了爬取網(wǎng)站數(shù)據(jù),提取結(jié)構(gòu)性數(shù)據(jù)而編寫的應(yīng)用框架。 可以應(yīng)用在包括數(shù)據(jù)挖掘,信息處理或存儲(chǔ)歷史數(shù)據(jù)等一系列的程序中陈惰。
本文編寫一個(gè)簡(jiǎn)單的Python 爬蟲用于抓取http://desk.zol.com.cn/的部分壁紙。
開發(fā)環(huán)境是mac OS ,python 版本是2.7.
step1 需要先安裝python 的虛擬環(huán)境毕籽。virtualenv可以搭建虛擬且獨(dú)立的python環(huán)境抬闯,可以使每個(gè)項(xiàng)目環(huán)境與其他項(xiàng)目獨(dú)立開來,保持環(huán)境的干凈影钉,解決包沖突問題画髓。
pip install virtualenv
創(chuàng)建一個(gè)虛擬且獨(dú)立空間。env 是虛擬環(huán)境的名稱
virtualenv env
啟動(dòng)虛擬環(huán)境(就是運(yùn)行 目錄env/bin 下的activate 文件)
. env/bin/activate
step2 安裝Scrapy平委。
pip install Scrapy
安裝Python 圖形處理庫(kù),下載圖片時(shí)需要使用到這個(gè)庫(kù)奈虾。
pip install Pillow
step3 創(chuàng)建項(xiàng)目 ,download 是項(xiàng)目名稱。
scrapy startproject download
2 編寫爬蟲
-
定義抓取的Item廉赔。第一步是定義我們需要爬取的數(shù)據(jù)結(jié)構(gòu)肉微。
items.py
import scrapy class DownloadItem(scrapy.Item): # define the fields for your item here like: # name = scrapy.Field() image_urls = scrapy.Field() //圖片的網(wǎng)址 images = scrapy.Field() //圖片信息 scrapy 自動(dòng)獲取的 images_page_url = scrapy.Field() images_catalog = scrapy.Field() //圖片的存放目錄
-
編寫網(wǎng)絡(luò)爬蟲。在spiders目錄下新建一個(gè)文件dmoz_spider.py蜡塌,用于編寫爬蟲邏輯碉纳。我使用Chrome瀏覽器的開發(fā)者工具對(duì)網(wǎng)站的結(jié)構(gòu)進(jìn)行分析,使用scrapy 選擇器提取響應(yīng)的信息馏艾。
#!/usr/bin/env python # -*- coding: utf-8 -*- import scrapy from download.items import DownloadItem class DmozSpider(scrapy.Spider): name = "download" allowed_domains = ["zol.com.cn"] start_urls = [ "http://desk.zol.com.cn/" ] def parse(self, response): #連接到圖片內(nèi)容頁(yè)面 for sel in response.xpath('//a[@class="pic"]'): shortUrl = sel.xpath('@href').extract()[0] url = response.urljoin(shortUrl) yield scrapy.Request(url, callback=self.parse_article) #連接到內(nèi)容頁(yè)的調(diào)用劳曹,在回調(diào)函數(shù)處理奴愉。 #連接到圖片內(nèi)容頁(yè)面 for sel in response.xpath('//a[@class="title"]'): shortUrl = sel.xpath('@href').extract()[0] url = response.urljoin(shortUrl) yield scrapy.Request(url, callback=self.parse_article) #真正下載圖片的處理函數(shù) def parse_article(self, response): item = DownloadItem() bigImgUrl = response.xpath('//img[@id="bigImg"]/@src').extract() #獲取圖片的URL item['image_urls'] = bigImgUrl item['images_page_url'] = response.url url = response.url catalog = url.split('_')[-3] catalog = catalog.split('/')[-1] item['images_catalog'] = catalog #獲取圖片的目錄 用于存放圖片 yield item nextPageUrl = response.xpath('//a[@id="pageNext"]/@href').extract()[0] #下一頁(yè) if nextPageUrl.index('.html') >= 0: url = response.urljoin(nextPageUrl); yield scrapy.Request(url, callback=self.parse_article)
3 保存圖片
-
圖片的保存需要用到Scrapy 的圖片處理Pipe。在setting.py中設(shè)置铁孵。先使用
scrapy.pipelines.images.ImagesPipeline
保存圖片锭硼,再使用自己編寫的download.pipelines.DownloadPipeline
對(duì)圖片分類處理。在setting.py 中設(shè)置蜕劝。
BOT_NAME = 'download' SPIDER_MODULES = ['download.spiders'] NEWSPIDER_MODULE = 'download.spiders' #同時(shí)使用圖片和文件管道 ITEM_PIPELINES = { 'scrapy.pipelines.images.ImagesPipeline': 1, 'download.pipelines.DownloadPipeline':2, } IMAGES_STORE = '/Users/superzhan/Documents/project/python/Scrapy/download/' # 圖片存儲(chǔ)路徑
-
爬蟲抓去到的數(shù)據(jù)需要通過pipelines 來分類保存檀头。在pipelines.py 中對(duì)下載到的圖片進(jìn)行分類保存。
# -*- coding: utf-8 -*- import os import shutil class DownloadPipeline(object): #move file def process_item(self, item, spider): curPath = '/Users/superzhan/Documents/Project/python/Scrapy/download/' #分類后的圖片目錄 targetPath ='/Users/superzhan/Documents/Project/python/Scrapy/download/Img/' #創(chuàng)建分類目錄 catalog = item['images_catalog'] targetCatalog = os.path.join(targetPath,catalog) if False == os.path.exists(targetCatalog): os.mkdir(targetCatalog) images_path= item['images'][0]['path'] full_image_path = os.path.join(curPath,images_path) target_image_path = os.path.join(targetCatalog,full_image_path.split('/')[-1]) #分類 shutil.move(full_image_path,target_image_path) return item
-
最后切換到項(xiàng)目的根目錄岖沛,執(zhí)行
scrapy crawl download -o items.json
開始抓取圖片暑始。
4 代碼下載
百度網(wǎng)盤https://pan.baidu.com/s/1nv32Y6l
實(shí)際使用時(shí)需要修改setting.py和pipelines.py的下載路徑。