ASCII码转换

时间:2017-02-14 10:52:20

标签: python python-2.7 ascii

您好我正在尝试通过python 2.7上的URL保存图像。有些网址包含特殊字符。 比如:http://homegrown.co.in/wp-content/uploads/2014/06/Pl%C3%B6tzlich-Am-Meer.jpg并且有很多具有特殊字符的网址。

我通过以下代码保存网址,但收到错误:

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之后没有,我仍然面临同样的问题。

1 个答案:

答案 0 :(得分:-1)

您可以在保存之前使用urllib.quote(filename)

相关问题