嗨我想通過URL在Python 2.7上保存圖像。有一些網址喜歡包含特殊字符。 像:http://homegrown.co.in/wp-content/uploads/2014/06/Pl%C3%B6tzlich-Am-Meer.jpg
和有一些特殊字符的網址很多。ASCII碼轉換
我對下面的代碼保存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)
我應該如何抓住這一錯誤並繼續我的過程。因爲我正在運行繼續循環,此時停止。如果有解決方案從這些網址保存圖像,那麼它很棒,否則請幫我繞過這個錯誤,並繼續我的過程。我的循環內我從其他文件導入此功能。
沒有做完sys.reload
後,我仍然面臨同樣的問題。
[UnicodeEncodeError:'ascii'編解碼器無法對特殊名稱進行編碼字符]的可能重複(http://stackoverflow.com/questions/31137552/unicodeencodeerror-ascii-codec-cant-encode-character-at-special -name) –
「filename」來自哪裏?如果它是一個unicode字符串,那麼您需要確保它是用文件系統支持的東西進行編碼的。 –