【问题标题】:ASCII codes convertionASCII码转换
【发布时间】: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之后没有,我仍然面临同样的问题。

【问题讨论】:

标签: python python-2.7 ascii


【解决方案1】:

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

【讨论】:

  • 你能解释一下如何
  • 越早越好。您可以在调用函数时使用它:save_image_from_url(url, urllib.quote(filename)) 在第 340 行或之前,初始化文件名​​时。
  • 是的,太棒了,一个笨拙的解决方法,而不是正确解决源问题...学习 unicode 和编码,你会省去很多痛苦。
猜你喜欢
  • 1970-01-01
  • 2013-11-04
  • 1970-01-01
  • 1970-01-01
  • 2016-09-14
  • 2011-06-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多