【发布时间】:2020-06-19 07:49:29
【问题描述】:
我正在尝试抓取网站(例如 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(搜索)到 TypeError(需要字符串参数,得到' bytes'),原因总是run.add_picture 行。
现在的代码会引发io.UnsupportOperation 异常。
【问题讨论】:
标签: python python-3.x python-docx