2017-02-14 162 views
0

嗨我想通過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後,我仍然面臨同樣的問題。

+0

[UnicodeEncodeError:'ascii'編解碼器無法對特殊名稱進行編碼字符]的可能重複(http://stackoverflow.com/questions/31137552/unicodeencodeerror-ascii-codec-cant-encode-character-at-special -name) –

+0

「filename」來自哪裏?如果它是一個unicode字符串,那麼您需要確保它是用文件系統支持的東西進行編碼的。 –

回答

-1

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

+0

你能解釋一下 –

+0

這個越早越好。在初始化文件名​​時,可以在第340行或之前調用函數''save_image_from_url(url,urllib.quote(filename))''時使用它。 – VdF

+0

是的,很好,一個非常好的解決方法,而不是正確地解決源代碼問題......瞭解unicode和編碼,您將爲自己節省很多痛苦。 –