社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

scrapy 将抓取内容中的图片下载到本地并替换内容中的原始图片

234553790 • 7 年前 • 401 次点击  

使用scrapy采集的文章里面有很多图片,都是远程图片,我想把这些远程图片都下载下来,然后把图片地址全都改成相对路径。

比如这篇文章的内容 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("//div[@id='content']//h1[@class='entry-title']/text()").extract()[0]
    article_imgs = response.xpath("//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("//div[@id='content']/article/div[@class='entry-content']").extract()[0]
    item['cimage_urls'] = response.xpath("//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可以下载图片,但只能将下载的图片存到一个字段里。

所以请教一下大家在这种情况下是怎么操作的?

万分感谢。

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/4165
 
401 次点击