鍍金池/ 問答/人工智能  數(shù)據(jù)分析&挖掘  Python  網(wǎng)絡安全  HTML/ scrapy 將抓取內(nèi)容中的圖片下載到本地并替換內(nèi)容中的原始圖片

scrapy 將抓取內(nèi)容中的圖片下載到本地并替換內(nèi)容中的原始圖片

使用scrapy采集的文章里面有很多圖片,都是遠程圖片,我想把這些遠程圖片都下載下來,然后把圖片地址全都改成相對路徑。

比如這篇文章的內(nèi)容
http://news.163.com/17/1115/2...

里面的圖片路徑都是類似 http://dingyue.nosdn.127.net/... 這種

我想把里面的圖片都下載到本地,然后再把路徑保存再item 里面。

    def parse_article(self, response):
        item = response.meta['item']
        item['title'] = response.xpath("http://div[@id='content']//h1[@class='entry-title']/text()").extract()[0]
        article_imgs = response.xpath("http://div[@id='content']/article/div[@class='entry-content']//img")
        for img in article_imgs:
            img_src = img.xpath("/@src").extract()[0]
            file_name = os.path.basename(img_src)
            real_name = file_name.split('.')[-2]
            print("圖片名稱", real_name)
            save_path = 'images/shopify/' + str(real_name)
            print("保存路徑", save_path)
            local_path = self.save_img(img_src, save_path)
            http_img_path = urljoin('http://www.tiangr.com', '/wp_content/uploads/' + local_path)
            print("替換路徑", http_img_path)
            ####################
            到這里之后不知道該怎么替換原來的圖片路徑。
            ####################
            
        item['content'] = response.xpath("http://div[@id='content']/article/div[@class='entry-content']").extract()[0]
        item['cimage_urls'] = response.xpath("http://div[@id='content']//header[@class='entry-header']/img//@src").extract()     # 提取圖片鏈接
        yield item

    def save_img(self, img_url, file_name):
        """
        保存圖片
        :param img_url 圖片地址
        :param file_name 文件名稱
        :return:
        """
        image_path = img_url.split('.')
        extension = image_path.pop()
        if len(extension) > 3:
            extension = 'jpg'
        img_url = urljoin('http://dingyue.nosdn.127.net', img_url)
        u = urllib.request.urlopen(img_url)
        data = u.read()
        f = open(file_name + '.' + extension, 'wb')
        f.write(data)
        f.close()
        return file_name + '.' + extension

我在看文檔的時候,看到雖然scrapy有ImagePipeline可以下載圖片,但只能將下載的圖片存到一個字段里。

所以請教一下大家在這種情況下是怎么操作的?

萬分感謝。

回答
編輯回答
冷溫柔

您好,請問下這個問題您解決了嗎?我也遇到了這種需求,能否一起探討下?感謝。

2017年12月20日 09:50