2014-02-20 121 views
0

我想製作一個程序從一些url下載jpg文件(日本漫畫),我在網上看到了一些例子,但它們不適用於我的情況:嘗試通過python下載urllib2下載jpg文件時出錯

import urllib2 
jpgfile = urllib2.urlopen("http://mangas2013.centraldemangas.com.br/attack_on_titan/attack_on_titan001-01.jpg") 
output = open('attack_on_titan001-01.jpg','wb') 
output.write(jpgfile.read()) 
output.close() 

有了這個網址,我得到了一個28kb的jpg文件文件(原始爲120kb),當我嘗試打開時,圖像不會出現在Windows圖片瀏覽器中......這很奇怪,因爲我可以下載並查看jpg文件從其他網站使用相同的代碼...

我是一個Python新手,所以嘗試給我最簡單的答案可能。

+0

也許服務器試圖阻止您下載? –

+0

你可以嘗試'請求'。 'requests.get(url)'然後'f.write(response.content)'。 –

回答

0

您可以嘗試使用urllib.urlretrieve()而不是urllib2.urlopen

import urllib 
jpg_filename, headers = urllib.urlretrieve('http://mangas2013.centraldemangas.com.br/attack_on_titan/attack_on_titan001-01.jpg', 'attack_on_titan001-01.jpg') 

編輯:我重新讀你的問題,我不確定爲什麼該網站特別是不起作用。這可能是因爲在訪問該文件之前需要進行身份驗證。檢查你得到什麼迴應:

import urllib2 
jpgfile = urllib2.urlopen("http://mangas2013.centraldemangas.com.br/attack_on_titan/attack_on_titan001-01.jpg") 
print jpgfile.getcode() 
print jpgfile.read() 

這可能是一個重定向,因爲缺乏身份驗證。

+0

我得到了同樣的錯誤,你是否嘗試運行你的代碼? –

+0

您很可能需要在該網站上進行身份驗證才能訪問jpeg文件。您可以使用代理服務器和瀏覽器查看有效的請求以查看該網站用於身份驗證的內容,但我確定您違反了某些服務條款。它可能需要設置正確的cookie值。退房http://stackoverflow.com/a/8206372/2337592 –

+0

我得到了一個長的HTML代碼作爲迴應,代碼來自漫畫的主頁:http://centraldemangas.com.br/mangas/info/attack-上泰坦 –