2012-05-31 36 views
0

我想從網站獲取圖像,但我不知道自己做錯了什麼。 這是我的代碼:試圖用python獲取圖像

import httplib2 

h = httplib2.Http('.cache') 

response, content = h.request('http://1.bp.blogspot.com/-KSBzFF0bIyU/TtFyj-KgC0I/AAAAAAAABEo/o43IoY_9Bec/s1600/praia-de-ponta-verde-maceio.jpg') 

print(response.status) 

with open('maceio.jpg', 'wb') as f: 
    print(content, file = f) 

-------------------------------------------------------------------------------- 

200 
Traceback (most recent call last): 
    File "/home/matheus/workspace/Get Link/new_method_v2.py", line 12, in <module> 
    print(content, file = f) 
TypeError: 'str' does not support the buffer interface 
+0

[類型錯誤:「STR」不支持緩衝器接口]的可能重複:(http://stackoverflow.com/questions/5471158/typeerror-str只使用file.write()方法寫內容到文件-does-not-support-the-buffer-interface) –

回答

2

該錯誤是由下面的行引起的:

print(content, file = f) 

print隱含轉換命名content爲字符串(str對象)bytes對象,它不能被寫入到一個二進制模式的文件,因爲Python不知道使用哪種字符編碼。

你爲什麼要走print繞道呢?

with open('maceio.jpg', 'wb') as f: 
    f.write(content) 
+0

謝謝!如果可能,你可以多談談一下「g.write()」嗎? – matheus

+1

查看文檔:http://docs.python.org/library/stdtypes.html#file.write – Matthias