昨天自己搞了一个下午加晚上,真的是心力憔悴。主要就是不知道imagespipeline怎么使用,问题在代码中有解释.
在settings.py中设置
ITEM_PIPELINES = {
#'car_bsj.pipelines.CarBsjPipeline': 300,
'car_bsj.pipelines.CARBSJImagesPipeline': 1
}
#这里是储存文件的文件目录
IMAGES_STORE = os.path.join(os.path.dirname(os.path.dirname(__file__)),'images')
直接上代码
spider.py
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule
from car_bsj.items import CarBsjItem
class BsjSpider(CrawlSpider):
name = 'bsj'
allowed_domains = ['autohome.com.cn']
start_urls = ['https://car.autohome.com.cn/pic/series/162.html']
rules = (
Rule(LinkExtractor(allow=r'.+pic/series/162-.+\.html'),
callback='parse_item', follow=True),
)
def parse_item(self, response):
box_title = response.xpath("//div[@class='uibox']/div/text()").get().strip()
imgs = response.xpath("//div[@class='uibox-con carpic-list03 border-b-solid']//li")
for img in imgs:
img_url ='https:' + img.xpath(".//img/@src").get()
#我们这里获取的是高清图不是缩略图,对比两者url
img_url = img_url.replace('240x180_0_q95_c42','800x0_1_q95')
img_title = img.xpath(".//img/@alt").get().strip()
#使用imagespipelines的图片地址一定要是列表,否则会出错
item = CarBsjItem(image_urls= [img_url],img_title =img_title,box_title=box_title)
yield item
from scrapy.pipelines.images import ImagesPipeline
import os
from car_bsj import settings
class CarBsjPipeline(object):
def process_item(self, item, spider):
return item
class CARBSJImagesPipeline(ImagesPipeline):
#info是类中自定义的一个方法,self.info()表示在类的其他实例方法中调用这个方法。
def get_media_requests(self, item, info):
#继承imagespipline中的get_media_requests方法,该方法主要是发送下载请求
results = super(CARBSJImagesPipeline, self).get_media_requests(item, info)
for result in results:
result.item = item
print(results)
return results
def file_path(self, request, response=None, info=None):
#继承file_path方法储存文件
path = super(CARBSJImagesPipeline, self).file_path(request, info)
urlpath = os.path.join(settings.IMAGES_STORE,request.item['box_title'])
if not os.path.exists(urlpath):
print('='*10)
os.mkdir(urlpath)
img_name =path.replace('full/',request.item['img_title'])
img_path = os.path.join(urlpath,img_name)
return img_path
结果
我没有等程序运行完