2012-08-01 103 views
12

我試圖打開一個網站使用urllib.request.urlopen((我後面的是公司Proxy)),但我得到的錯誤:的Python 3 - urllib的,HTTP錯誤407:需要代理身份驗證

urllib.error.HTTPError: HTTP Error 407: Proxy Authentication Required 

我可以在urllib.request.getproxies()中找到代理,但是如何指定要使用的用戶名和密碼?我無法在官方文檔中找到解決方案。

+0

你見過http://stackoverflow.com/questions/34079/how-to-specify-an-authenticated-proxy-for-a-python-http-connection? http://docs.python.org/library/urllib2.html#urllib2-examples底部的例子。 – katrielalex 2012-08-01 16:01:46

+0

是的,但這是Python2.7他們沒有重構Python3 3中的整個urllib包嗎? – Lanaru 2012-08-01 16:03:42

+1

他們並沒有從根本上改變界面 - 只是將事情轉移了一下。 'ProxyHandler'現在位於['urllib.request.ProxyHandler'](http://docs.python.org/release/3.0.1/library/urllib.request.html#urllib.request.ProxyHandler) – katrielalex 2012-08-01 16:04:49

回答

21
import urllib.request as req 

proxy = req.ProxyHandler({'http': r'http://username:[email protected]:port'}) 
auth = req.HTTPBasicAuthHandler() 
opener = req.build_opener(proxy, auth, req.HTTPHandler) 
req.install_opener(opener) 
conn = req.urlopen('http://google.com') 
return_str = conn.read() 
+3

謝謝。沒有提供用戶名和密碼的情況下沒有辦法做到這一點? – 2015-02-08 18:26:02

+3

如果您擔心在您的源代碼中使用硬編碼的證書(並因此泄漏到git或其他VCS工件等中),那麼最好的方法是使用像configparser或YAML或JSON之類的東西來存儲證書在他們自己的單獨文件中。從配置設置中動態構建ProxyHandler URL。這可以讓您的資料來源在保密的情況下可讀。 – 2015-08-05 19:07:06

+1

一個小提示:對我來說,他有「@url:port」我實際上使用了機器名「@machine:port」,而不是完整的URL。 – mcherm 2016-02-02 15:32:36