Python Scrapy圖片爬取原理及代碼實例
1.在爬蟲文件中只需要解析提取出圖片地址,然后將地址提交給管道
在管道文件對圖片進行下載和持久化存儲
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.管道類的修改
原本管道類繼承的object,處理item對象使用時process_item方法,該方法不能發送請求,要想對圖片地址發送請求,需要繼承ImagesPipeline類,然后重寫該類中的三個方法:get_media_requests,file_path,item_completed
from scrapy.pipelines.images import ImagesPipelineimport scrapyclass ImgproPipeline(ImagesPipeline): #對某一個媒體資源進行請求發送 #item就是接收到的spider提交過來的item def get_media_requests(self, item, info): yield scrapy.Request(item[’src’]) #制定媒體數據存儲的名稱 def file_path(self, request, response=None, info=None): name = request.url.split(’/’)[-1] print(’正在下載:’,name) return name #將item傳遞給下一個即將給執行的管道類 def item_completed(self, results, item, info): return item
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持好吧啦網。
相關文章:
1. Android打包篇:Android Studio將代碼打包成jar包教程2. Python使用urlretrieve實現直接遠程下載圖片的示例代碼3. SpringBoot+TestNG單元測試的實現4. Springboot 全局日期格式化處理的實現5. vue實現web在線聊天功能6. 解決Android Studio 格式化 Format代碼快捷鍵問題7. 完美解決vue 中多個echarts圖表自適應的問題8. JavaScript實現頁面動態驗證碼的實現示例9. Java使用Tesseract-Ocr識別數字10. JavaEE SpringMyBatis是什么? 它和Hibernate的區別及如何配置MyBatis
