2016-01-22 167 views
0

我試圖下載一個PDF格式,但我得到以下錯誤:HTTP錯誤403:禁止HTTP錯誤403:禁止

我知道服務器阻止不管是什麼原因,但我似乎無法找到一個辦法。請幫忙。

import urllib.request 
import urllib.parse 
import requests 


def download_pdf(url): 

full_name = "Test.pdf" 
urllib.request.urlretrieve(url, full_name) 


try: 
url =   ('http://papers.xtremepapers.com/CIE/Cambridge%20IGCSE/Mathematics%20(0580)/0580_s03_qp_1.pdf') 

print('initialized') 

hdr = {} 
hdr = { 
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_2)  AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36', 
'Content-Length': '136963', 
} 



print('HDR recieved') 

req = urllib.request.Request(url, headers=hdr) 

print('Header sent') 

resp = urllib.request.urlopen(req) 

print('Request sent') 

respData = resp.read() 

download_pdf(url) 


print('Complete') 

except Exception as e: 
print(str(e)) 
+0

如果服務器阻塞,可能不是一個簡單的方法。禁止意味着你不被允許。 – Zizouz212

回答

5

你似乎已經意識到這一點;遠程服務器顯然是檢查用戶代理頭並拒絕來自Python的urllib的請求。但urllib.request.urlretrieve()不允許更改HTTP頭,但是,你可以使用urllib.request.URLopener.retrieve()

import urllib.request 

opener = urllib.request.URLopener() 
opener.addheader('User-Agent', 'whatever') 
filename, headers = opener.retrieve(url, 'Test.pdf') 

注:您正在使用Python 3,現在這些功能被認爲是"Legacy interface"的一部分,而URLopener已被棄用。出於這個原因,你不應該在新的代碼中使用它們。

上面一邊,你會很容易訪問一個URL。你的代碼輸入requests,但你不用它 - 你應該,因爲它比urllib容易得多。這適用於我:

import requests 

url = 'http://papers.xtremepapers.com/CIE/Cambridge%20IGCSE/Mathematics%20(0580)/0580_s03_qp_1.pdf' 
r = requests.get(url) 
with open('0580_s03_qp_1.pdf', 'wb') as outfile: 
    outfile.write(r.content) 
+1

雖然很好 - 它沒有解釋403錯誤的原因。 – Zizouz212

+1

問題不是要求原因。 – Zain