我试图使用ImagesPipeline下载图像,结果只能得到一张图片(最后一张);参见屏幕截图:

我的目标网站是https://sc.chinaz.com/tupian/
你可以检查我的代码:
#This is spider:
import scrapy
from imgPro.items import ImgproItem
from PIL import Image
class ImgSpider(scrapy.Spider):
name = 'img'
#allowed_domains = ['www.xxx.com']
start_urls = ['https://sc.chinaz.com/tupian/']
def parse(self, response):
div_list = response.xpath('//*[@id="container"]/div')
# print(div_list)
# url = 'https://sc.chinaz.com'
for div in div_list:
img_src = 'https:' + div.xpath('./div/a/img/@src2')[0].extract()
print(img_src)
item = ImgproItem()
item['src'] = img_src
yield item这是我的管道:
import scrapy
from scrapy.pipelines.images import ImagesPipeline
class imagePipeLine(ImagesPipeline):
def get_media_requests(self, item, info):
yield scrapy.Request(item['src'])
def file_path(self, request, response=None, info=None, *, item=None):
imag_name = request.url.split('/')[-1]
return imag_name
def item_completed(self, results, item, info):
return item我该怎么做才能得到所有的图像?
发布于 2021-03-21 15:37:55
在for-循环中的parse()中,您要遍历所有图像的列表,但是在循环之后,只有最后一个图像保存在img_src中,并且永远不会返回到以前的图像。因此,您要么需要在得到每个图像的img_src后立即处理它:
for div in div_list:
img_src = 'https:' + div.xpath('./div/a/img/@src2')[0].extract()
print(img_src)
# now process this image或者将它们全部保存在一个列表中,然后处理整个列表:
all_img_srcs = []
for div in div_list:
img_src = 'https:' + div.xpath('./div/a/img/@src2')[0].extract()
print(img_src)
all_img_srcs.append(img_src)
# now process all the images on the list或者也许
def parse(self, response):
div_list = response.xpath('//*[@id="container"]/div')
items = []
for div in div_list:
img_src = 'https:' + div.xpath('./div/a/img/@src2')[0].extract()
print(img_src)
item = ImgproItem()
item['src'] = img_src
items.append(item)
yield itemshttps://stackoverflow.com/questions/66733590
复制相似问题