2017-01-25 49 views
0

我試圖下載一個圖像,但它似乎工作。是否被ddos保護攔截?urlretrieve不適用於本網站

這裏是代碼: 「test.png」

urllib.request.urlretrieve("http://archive.is/Xx9t3/scr.png", "test.png") 

基本上下載圖像我使用python3,因此在urlretrieve之前使用urllib.request。

import urllib.request 

也有。

任何方式我可以下載圖像?謝謝!

+1

你如果你發佈更多的信息,比如你遇到了什麼錯誤,可能會有更多的答案。 – shazow

回答

1

由於我無法想象的原因,服務器需要一個衆所周知的用戶代理。所以,你必須假裝例如使用Firefox和它接受發送圖像:

# first build a request object 
req = urllib.request.Request("http://archive.is/Xx9t3/scr.png", 
     headers = { 
      'User-agent': 
       'Mozilla/5.0 (Windows NT 5.1; rv:43.0) Gecko/20100101 Firefox/43.0'}) 

#then use it 
resp = urllib.request.urlopen(req) 
with open("test.png","wb") as fd: 
    fd.write(resp.read()) 

而是愚蠢的,但是當一個服務器管理員發瘋,只不過是既愚蠢又是...

+0

謝謝工作!也奇怪,但使用write()沒有標題以及使用:f.write(requests.get(「http://archive.is/Xx9t3/scr.png」).content) – user3294913

0

我建議你用requests,基本上你想獲得的圖像是被禁止的方式,檢查:

import requests 
import shutil 

r = requests.get('http://archive.is/Xx9t3/scr.png', stream=True) 
if r.status_code == 200: 
    with open("test.png", 'wb') as f: 
     r.raw.decode_content = True 
     shutil.copyfileobj(r.raw, f) 

這個片段改編自here

魔術後面是如何檢索資源,requests該部分是stream=True行。有些服務器更受這種方法的限制,以拉取媒體等資源。

相關問題