Python Scrapy圖片爬取原理及代碼實(shí)例
1.在爬蟲(chóng)文件中只需要解析提取出圖片地址,然后將地址提交給管道
在管道文件對(duì)圖片進(jìn)行下載和持久化存儲(chǔ)
class ImgSpider(scrapy.Spider): name = ’img’ # allowed_domains = [’www.xxx.com’] start_urls = [’http://www.521609.com/daxuemeinv/’] url = ’http://www.521609.com/daxuemeinv/list8%d.html’ pageNum = 1 def parse(self, response): li_list = response.xpath(’//*[@id='content']/div[2]/div[2]/ul/li’) for li in li_list: img_src = ’http://www.521609.com’+li.xpath(’./a[1]/img/@src’).extract_first() item = ImgproItem() item[’src’] = img_src yield item
2.配置文件修改
配置文件要增加IMAGES_STORE = ’./imgsLib’表明圖片存放的路徑
3.管道類(lèi)的修改
原本管道類(lèi)繼承的object,處理item對(duì)象使用時(shí)process_item方法,該方法不能發(fā)送請(qǐng)求,要想對(duì)圖片地址發(fā)送請(qǐng)求,需要繼承ImagesPipeline類(lèi),然后重寫(xiě)該類(lèi)中的三個(gè)方法:get_media_requests,file_path,item_completed
from scrapy.pipelines.images import ImagesPipelineimport scrapyclass ImgproPipeline(ImagesPipeline): #對(duì)某一個(gè)媒體資源進(jìn)行請(qǐng)求發(fā)送 #item就是接收到的spider提交過(guò)來(lái)的item def get_media_requests(self, item, info): yield scrapy.Request(item[’src’]) #制定媒體數(shù)據(jù)存儲(chǔ)的名稱(chēng) def file_path(self, request, response=None, info=None): name = request.url.split(’/’)[-1] print(’正在下載:’,name) return name #將item傳遞給下一個(gè)即將給執(zhí)行的管道類(lèi) def item_completed(self, results, item, info): return item
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. ASP 信息提示函數(shù)并作返回或者轉(zhuǎn)向2. asp(vbs)Rs.Open和Conn.Execute的詳解和區(qū)別及&H0001的說(shuō)明3. CSS hack用法案例詳解4. PHP設(shè)計(jì)模式中工廠模式深入詳解5. 用css截取字符的幾種方法詳解(css排版隱藏溢出文本)6. ASP+ajax實(shí)現(xiàn)頂一下、踩一下同支持與反對(duì)的實(shí)現(xiàn)代碼7. JSP數(shù)據(jù)交互實(shí)現(xiàn)過(guò)程解析8. ThinkPHP5實(shí)現(xiàn)JWT Token認(rèn)證的過(guò)程(親測(cè)可用)9. asp中response.write("中文")或者js中文亂碼問(wèn)題10. PHP session反序列化漏洞超詳細(xì)講解
