嗨,我正在尝试通过Python2.7上的URL保存图像。有一些像包含特殊字符的urls。比如: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)我应该如何捕捉这个错误并继续我的过程。当我运行连续循环时,它在这一点上停止了。如果有一个解决方案,以保存图像从这些网址,那么它很好,否则请帮助我绕过这个错误,并继续我的过程。在我的for循环中,我从其他文件导入了这个函数。
没有,在做了sys.reload之后,我仍然面临着同样的问题。
发布于 2017-02-14 19:00:17
您可以在保存之前使用urllib.quote(filename)。
https://stackoverflow.com/questions/42224253
复制相似问题