需求:爬取站長素材中的高清圖片
一.數據解析(圖片的地址)
通過xpath解析出圖片src的屬性值。
只需要將img的src的屬性值進行解析,提交到管道, 管道就會對圖片的src進行請求發送獲取圖片
spider文件
class ImgSpider(scrapy.Spider): name = 'img' # allowed_domains = ['www.xxx.com'] start_urls = ['http://sc.chinaz.com/tupian/'] def parse(self, response): src_list = response.xpath('//div[@id="container"]/div') # print(src_list) for src_item in src_list: # 圖片懶加載(當瀏覽器滑動到圖片時src2屬性變為src屬性) # scrapy不會滑動到圖片,所以使用src2屬性(偽屬性) src_content = src_item.xpath('./div/a/img/@src2').extract_first() print(src_content) item = ImgsproItem() item['src'] = src_content yield item
二.在管道文件中自定義一個基於ImagesPipeline的一個管道類
實現父類的3個方法
-get_media_requests
-file_path
-item_completed
pipeline文件:
import scrapy from scrapy.pipelines.images import ImagesPipeline class ImgsproPipeline(object): item = None def process_item(self, item, spider): return item # ImagesPipeline用於文件下載管道類,下載過程支持異步和多線程 class ImgPipeLine(ImagesPipeline): # 對item中的圖片進行請求操作 def get_media_requests(self, item, info): yield scrapy.Request(item['src']) # 定制圖片的名稱 def file_path(self, request, response=None, info=None): imgName = request.url.split('/')[-1] return imgName # def item_completed(self, results, item, info): return item # 傳遞到下一個即將被執行的管道類
三.在配置文件中指定圖片存儲 的目錄
IMAGES_STORE ='./img'
配置文件:
#USER_AGENT = 'firstBlood (+http://www.yourdomain.com)' USER_AGENT = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36' # 偽裝請求載體身份 # Obey robots.txt rules # ROBOTSTXT_OBEY = True ROBOTSTXT_OBEY = False #可以忽略或者不遵守robots協議 #只顯示指定類型的日志信息 LOG_LEVEL='ERROR' # 表示最終圖片存儲的目錄 IMAGES_STORE ='./imgs' # Configure maximum concurrent requests performed by Scrapy (default: 16) #CONCURRENT_REQUESTS = 32 # Configure item pipelines # See https://doc.scrapy.org/en/latest/topics/item-pipeline.html ITEM_PIPELINES = { 'imgsPro.pipelines.ImgsproPipeline': 300, 'imgsPro.pipelines.ImgPipeLine': 200, }