【Python】抓取网页图片并保存到本地和Word(ImagePIL和python-docx的使用)

记录爬虫利用pyquery爬虫保存图片时遇到的一些问题:

1. cannot write mode P as JPEG

解决办法:将模式“P”转化为“RGB”模式 

if img.mode == "P":
    img = img.convert('RGB')

2. (PIL) Image.save保存图片后,图片大小为0KB

解决办法:设置quality参数

im.save(img_name, quality=95)

3. Inches(self.px_width / self.horz_dpi) ZeroDivisionError: division by zero

解决办法:这边是由于dpi为0导致的报错,修改图片的dpi后解决

源码的解释:

        Return a new picture shape added in its own paragraph at the end of
        the document. The picture contains the image at
        *image_path_or_stream*, scaled based on *width* and *height*. If
        neither width nor height is specified, the picture appears at its
        native size. If only one is specified, it is used to compute
        a scaling factor that is then applied to the unspecified dimension,
        preserving the aspect ratio of the image. The native size of the
        picture is calculated using the dots-per-inch (dpi) value specified
        in the image file, defaulting to 72 dpi if no value is specified, as
        is often the case.

 部分代码:

with open(save_path, 'wb') as f:
    res = requests.get(picture_url).content  
    f.write(res)
    f.close()
im = ImagePIL.open(save_path) 
if im.mode == "P":
    im = im.convert('RGB')
save_path_modify = save_path.replace('.jpg', 'modify.jpg')
im.save(save_path_modify, dpi=(300, 300), quality=100)
document.add_picture(save_path_modify, width=Inches(5))

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值