不懂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 item2.配置文件修改
配置文件要增加IMAGES_STORE = './imgsLib'表明圖片存放的路徑
3.管道類的修改
原本管道類繼承的object,處理item對象使用時process_item方法,該方法不能發送請求,要想對圖片地址發送請求,需要繼承ImagesPipeline類,然后重寫該類中的三個方法:get_media_requests,file_path,item_completed
from scrapy.pipelines.images import ImagesPipeline
import scrapy
class 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感謝你能夠認真閱讀完這篇文章,希望小編分享Python Scrapy圖片爬取的方法內容對大家有幫助,同時也希望大家多多支持億速云,關注億速云行業資訊頻道,遇到問題就找億速云,詳細的解決方法等著你來學習!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。