【发布时间】:2017-07-02 15:08:18
【问题描述】:
您好,我正在尝试通过 python 2.7 上的 URL 保存图像。有一些 url,比如包含特殊字符。
比如:http://homegrown.co.in/wp-content/uploads/2014/06/Pl%C3%B6tzlich-Am-Meer.jpg 并且有很多带有一些特殊字符的 url。
我正在通过以下代码保存 URL,但出现错误:
def save_image_from_url(url, filename):
print('Saving {} locally'.format(url))
image = requests.get(url)
with open(os.path.join(IMG_DIR_ABS, filename), 'wb') as f:
f.write(image.content)
f.close()
错误
File "/home/wp-migrate/migrate.py", line 340, in seperate_img_blocks
save_image_from_url(url, filename)
File "/home/wp-migrate/s3.py", line 50, in save_image_from_url
with open(os.path.join(IMG_DIR_ABS, filename), 'wb') as f:
UnicodeEncodeError: 'ascii' codec can't encode character u'\xf6' in position 16: ordinal not in range(128)
我应该如何发现这个错误并继续我的过程。当我运行持续循环时,此时会停止。如果有从这些 url 保存图像的解决方案,那么它很好,否则请帮助我绕过这个错误并继续我的过程。在我的 for 循环中,我正在从其他文件中导入此函数。
在sys.reload之后没有,我仍然面临同样的问题。
【问题讨论】:
-
“文件名”从何而来?如果它是一个 unicode 字符串,你要确保它被编码在你的文件系统支持的东西中。
标签: python python-2.7 ascii