Python使用Scrapy爬蟲框架全站爬取圖片并保存本地的實(shí)現(xiàn)代碼
大家可以在Github上clone全部源碼。
Github:https://github.com/williamzxl/Scrapy_CrawlMeiziTu
Scrapy官方文檔:http://scrapy-chs.readthedocs.io/zh_CN/latest/index.html
基本上按照文檔的流程走一遍就基本會(huì)用了。
Step1:
在開(kāi)始爬取之前,必須創(chuàng)建一個(gè)新的Scrapy項(xiàng)目。 進(jìn)入打算存儲(chǔ)代碼的目錄中,運(yùn)行下列命令:
scrapy startproject CrawlMeiziTu
該命令將會(huì)創(chuàng)建包含下列內(nèi)容的 tutorial 目錄:
CrawlMeiziTu/ scrapy.cfg CrawlMeiziTu/ __init__.py items.py pipelines.py settings.py middlewares.py spiders/ __init__.py ... cd CrawlMeiziTu scrapy genspider Meizitu http://www.meizitu.com/a/list_1_1.html
該命令將會(huì)創(chuàng)建包含下列內(nèi)容的 tutorial 目錄:
CrawlMeiziTu/ scrapy.cfg CrawlMeiziTu/ __init__.py items.py pipelines.py settings.py middlewares.py spiders/ Meizitu.py __init__.py ...
我們主要編輯的就如下圖箭頭所示:
main.py是后來(lái)加上的,加了兩條命令,
from scrapy import cmdline cmdline.execute("scrapy crawl Meizitu".split())
主要為了方便運(yùn)行。
Step2:編輯Settings,如下圖所示
BOT_NAME = 'CrawlMeiziTu' SPIDER_MODULES = ['CrawlMeiziTu.spiders'] NEWSPIDER_MODULE = 'CrawlMeiziTu.spiders' ITEM_PIPELINES = { 'CrawlMeiziTu.pipelines.CrawlmeizituPipeline': 300, } IMAGES_STORE = 'D://pic2' DOWNLOAD_DELAY = 0.3 USER_AGENT = 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36' ROBOTSTXT_OBEY = True
主要設(shè)置USER_AGENT,下載路徑,下載延遲時(shí)間
Step3:編輯Items.
Items主要用來(lái)存取通過(guò)Spider程序抓取的信息。由于我們爬取妹子圖,所以要抓取每張圖片的名字,圖片的連接,標(biāo)簽等等
# -*- coding: utf-8 -*- # Define here the models for your scraped items # # See documentation in: # http://doc.scrapy.org/en/latest/topics/items.html import scrapy class CrawlmeizituItem(scrapy.Item): # define the fields for your item here like: # name = scrapy.Field() #title為文件夾名字 title = scrapy.Field() url = scrapy.Field() tags = scrapy.Field() #圖片的連接 src = scrapy.Field() #alt為圖片名字 alt = scrapy.Field()
Step4:編輯Pipelines
Pipelines主要對(duì)items里面獲取的信息進(jìn)行處理。比如說(shuō)根據(jù)title創(chuàng)建文件夾或者圖片的名字,根據(jù)圖片鏈接下載圖片。
# -*- coding: utf-8 -*- import os import requests from CrawlMeiziTu.settings import IMAGES_STORE class CrawlmeizituPipeline(object): def process_item(self, item, spider): fold_name = "".join(item['title']) header = { 'USER-Agent': 'User-Agent:Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36', 'Cookie': 'b963ef2d97e050aaf90fd5fab8e78633', #需要查看圖片的cookie信息,否則下載的圖片無(wú)法查看 } images = [] # 所有圖片放在一個(gè)文件夾下 dir_path = '{}'.format(IMAGES_STORE) if not os.path.exists(dir_path) and len(item['src']) != 0: os.mkdir(dir_path) if len(item['src']) == 0: with open('..//check.txt', 'a+') as fp: fp.write("".join(item['title']) + ":" + "".join(item['url'])) fp.write("\n") for jpg_url, name, num in zip(item['src'], item['alt'],range(0,100)): file_name = name + str(num) file_path = '{}//{}'.format(dir_path, file_name) images.append(file_path) if os.path.exists(file_path) or os.path.exists(file_name): continue with open('{}//{}.jpg'.format(dir_path, file_name), 'wb') as f: req = requests.get(jpg_url, headers=header) f.write(req.content) return item
Step5:編輯Meizitu的主程序。
最重要的主程序:
# -*- coding: utf-8 -*- import scrapy from CrawlMeiziTu.items import CrawlmeizituItem #from CrawlMeiziTu.items import CrawlmeizituItemPage import time class MeizituSpider(scrapy.Spider): name = "Meizitu" #allowed_domains = ["meizitu.com/"] start_urls = [] last_url = [] with open('..//url.txt', 'r') as fp: crawl_urls = fp.readlines() for start_url in crawl_urls: last_url.append(start_url.strip('\n')) start_urls.append("".join(last_url[-1])) def parse(self, response): selector = scrapy.Selector(response) #item = CrawlmeizituItemPage() next_pages = selector.xpath('//*[@id="wp_page_numbers"]/ul/li/a/@href').extract() next_pages_text = selector.xpath('//*[@id="wp_page_numbers"]/ul/li/a/text()').extract() all_urls = [] if '下一頁(yè)' in next_pages_text: next_url = "http://www.meizitu.com/a/{}".format(next_pages[-2]) with open('..//url.txt', 'a+') as fp: fp.write('\n') fp.write(next_url) fp.write("\n") request = scrapy.http.Request(next_url, callback=self.parse) time.sleep(2) yield request all_info = selector.xpath('//h3[@class="tit"]/a') #讀取每個(gè)圖片夾的連接 for info in all_info: links = info.xpath('//h3[@class="tit"]/a/@href').extract() for link in links: request = scrapy.http.Request(link, callback=self.parse_item) time.sleep(1) yield request # next_link = selector.xpath('//*[@id="wp_page_numbers"]/ul/li/a/@href').extract() # next_link_text = selector.xpath('//*[@id="wp_page_numbers"]/ul/li/a/text()').extract() # if '下一頁(yè)' in next_link_text: # nextPage = "http://www.meizitu.com/a/{}".format(next_link[-2]) # item['page_url'] = nextPage # yield item #抓取每個(gè)文件夾的信息 def parse_item(self, response): item = CrawlmeizituItem() selector = scrapy.Selector(response) image_title = selector.xpath('//h2/a/text()').extract() image_url = selector.xpath('//h2/a/@href').extract() image_tags = selector.xpath('//div[@class="metaRight"]/p/text()').extract() if selector.xpath('//*[@id="picture"]/p/img/@src').extract(): image_src = selector.xpath('//*[@id="picture"]/p/img/@src').extract() else: image_src = selector.xpath('//*[@id="maincontent"]/div/p/img/@src').extract() if selector.xpath('//*[@id="picture"]/p/img/@alt').extract(): pic_name = selector.xpath('//*[@id="picture"]/p/img/@alt').extract() else: pic_name = selector.xpath('//*[@id="maincontent"]/div/p/img/@alt').extract() #//*[@id="maincontent"]/div/p/img/@alt item['title'] = image_title item['url'] = image_url item['tags'] = image_tags item['src'] = image_src item['alt'] = pic_name print(item) time.sleep(1) yield item
總結(jié)
以上所述是小編給大家介紹的Python使用Scrapy爬蟲框架全站爬取圖片并保存本地的實(shí)現(xiàn)代碼,希望對(duì)大家有所幫助,如果大家啊有任何疑問(wèn)歡迎給我留言,小編會(huì)及時(shí)回復(fù)大家的!
- Python爬蟲框架Scrapy安裝使用步驟
- 零基礎(chǔ)寫python爬蟲之使用Scrapy框架編寫爬蟲
- 使用scrapy實(shí)現(xiàn)爬網(wǎng)站例子和實(shí)現(xiàn)網(wǎng)絡(luò)爬蟲(蜘蛛)的步驟
- scrapy爬蟲完整實(shí)例
- 深入剖析Python的爬蟲框架Scrapy的結(jié)構(gòu)與運(yùn)作流程
- 講解Python的Scrapy爬蟲框架使用代理進(jìn)行采集的方法
- Python的Scrapy爬蟲框架簡(jiǎn)單學(xué)習(xí)筆記
- 實(shí)踐Python的爬蟲框架Scrapy來(lái)抓取豆瓣電影TOP250
- 使用Python的Scrapy框架編寫web爬蟲的簡(jiǎn)單示例
- python爬蟲框架scrapy實(shí)戰(zhàn)之爬取京東商城進(jìn)階篇
- 淺析python實(shí)現(xiàn)scrapy定時(shí)執(zhí)行爬蟲
- Scrapy爬蟲多線程導(dǎo)致抓取錯(cuò)亂的問(wèn)題解決
相關(guān)文章
基于Python實(shí)現(xiàn)自動(dòng)化文檔整理工具
一個(gè)人可能會(huì)在計(jì)算機(jī)上存儲(chǔ)大量的照片、視頻和文檔文件,這些文件可能散落在不同的文件夾中,難以管理和查找。所以本文就來(lái)用Python制作一個(gè)自動(dòng)化文檔整理工具吧2023-04-04用python獲取txt文件中關(guān)鍵字的數(shù)量
這篇文章主要介紹了如何用python獲取txt文件中關(guān)鍵字的數(shù)量,幫助大家更好的理解和使用python,感興趣的朋友可以了解下2020-12-12Django如何利用uwsgi和nginx修改代碼自動(dòng)重啟
這篇文章主要介紹了Django如何利用uwsgi和nginx修改代碼自動(dòng)重啟問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-05-05python按修改時(shí)間順序排列文件的實(shí)例代碼
這篇文章主要介紹了python按修改時(shí)間順序排列文件的實(shí)例代碼,代碼簡(jiǎn)單易懂,非常不錯(cuò),具有一定的參考借鑒價(jià)值 ,需要的朋友可以參考下2019-07-07python中protobuf和json互相轉(zhuǎn)換應(yīng)用處理方法
protobuf目前有proto2和proto3兩個(gè)版本,本文所介紹的是基于proto3,在Python 3.6.9環(huán)境下運(yùn)行,本文記錄一下python中protobuf和json的相互轉(zhuǎn)換的處理方法,感興趣的朋友跟隨小編一起看看吧2022-12-12深入理解python中函數(shù)傳遞參數(shù)是值傳遞還是引用傳遞
這篇文章主要介紹了深入理解python中函數(shù)傳遞參數(shù)是值傳遞還是引用傳遞,涉及具體代碼示例,具有一定參考價(jià)值,需要的朋友可以了解下。2017-11-11python中h5py開(kāi)源庫(kù)的使用樣例詳解
這篇文章主要介紹了python中的h5py開(kāi)源庫(kù)的使用,本文只是簡(jiǎn)單的對(duì)h5py庫(kù)的基本創(chuàng)建文件,數(shù)據(jù)集和讀取數(shù)據(jù)的方式進(jìn)行介紹,需要的朋友可以參考下2022-05-05找Python安裝目錄,設(shè)置環(huán)境路徑以及在命令行運(yùn)行python腳本實(shí)例
這篇文章主要介紹了找Python安裝目錄,設(shè)置環(huán)境路徑以及在命令行運(yùn)行python腳本實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-03-03pycharm配置python環(huán)境的詳細(xì)圖文教程
PyCharm是一款功能強(qiáng)大的Python編輯器,具有跨平臺(tái)性,下面這篇文章主要給大家介紹了關(guān)于pycharm配置python環(huán)境的詳細(xì)圖文教程,文中通過(guò)圖文介紹的非常詳細(xì),需要的朋友可以參考下2023-01-01Python利用解析JSON實(shí)現(xiàn)主機(jī)管理
JSON 是一種獨(dú)立于編程語(yǔ)言的數(shù)據(jù)格式,因此在不同的編程語(yǔ)言中都有對(duì)應(yīng)的解析器和生成器,本文主要介紹了Python如何通過(guò)解析JSON實(shí)現(xiàn)主機(jī)管理,感興趣的小伙伴可以了解一下2023-12-12