我试图抓取一个网站(如imgur)上的图片,并将其添加到docx中
这是我的初始代码(这是函数的一部分。我已将其拆分为相关代码):
from PIL import Image
from urllib.request import urlopen
thisParagraph = document.sections[0].paragraphs[0]
run = thisParagraph.add_run()
# imgLink is a direct link to the image. Something like https://i.imgur.com/<name>.jpg
# online is a parsed-in boolean to determine if the image link is from an image hosting site
# or from the local machine
if (online):
imgLinkData = urlopen(imgLink )
img = Image.open(imgLinkData )
width, height = img.size
else:
img = Image.open(imgLink )
width, height = img.size
imgLinkData = imgLink
if (width > 250) or (height > 250):
if (height > width):
run.add_picture(imgLinkData, width=Cm(3), height=Cm(4) )
else:
run.add_picture(imgLinkData, width=Cm(4), height=Cm(3) )
else:
run.add_picture(imgLinkData)
在大多数情况下,如果imgLink指向我的本地系统(即,图像托管在我的PC上),则此功能可以正常工作
但是如果我引用一个url链接(online=True),我会得到各种类型的异常(在我试图修复它的过程中),范围从io.UnsupportOperation
(seek)到TypeError
(应该是字符串参数,得到“bytes”),原因总是run.add_picture
行
现在的代码抛出io.UnsupportOperation
异常
将图像保存到文件,然后使用文件路径作为
.add_picture()
的第一个参数。这大致类似于:或者,您可以创建一个包含图像的“内存中”文件(
io.BytesIO
),并使用该文件。第二种方法的优点是不需要访问文件系统Document.add_picture()
的接口需要str路径或类似文件的对象(打开文件或内存文件)作为其第一个参数:https://python-docx.readthedocs.io/en/latest/api/document.html#docx.document.Document.add_picture我想我可能已经解决了这个问题
基于this link,我对代码做了一些轻微的修改
我补充说:
然后我改变了:
到
这似乎已经成功地在我的docx文档中生成了这个图像,尽管我不知道为什么,除了urlopen返回的事实之外
还有请求。请返回
内容返回了一个
反对
Further reading甚至似乎表示反对使用
urllib
相关问题 更多 >
编程相关推荐