2013-08-20 13 views
0

定義:urllib2.ProxyHandler - 查詢

urllib2.ProxyHandler([proxies]) 

原因請求通過代理。如果提供了代理服務器,它必須是一個字典映射協議名稱到代理服務器的URL。缺省值是從環境變量_proxy中讀取代理列表。如果未設置代理環境變量,則在Windows環境中,代理設置可從註冊表的「Internet設置」部分獲得,而在Mac OS X環境中,將從OS X系統配置框架中檢索代理信息。

我的理解是,如果代理沒有設置爲顯式,它會檢測代理註冊表設置。

BUET當我運行下面的代碼:

import urllib2 
proxy_support = urllib2.ProxyHandler({}) 
print "1" 
opener = urllib2.build_opener(proxy_support) 
print "2" 
urllib2.install_opener(opener) 
print "3" 
response = urllib2.urlopen('http://google.com') 
print "4" 
html = response.read() 

我得到的錯誤:

1 
2 
3 
urllib2.URLError: <urlopen error [Errno 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond> 

這意味着在一段代碼是無法打開的網站。我不知道我錯在哪裏,不應該按照定義,urllib2.ProxyHandler,從註冊表中獲取代理,因爲我沒有明確設置代理?

回答

1

shouldn't as per definition , urllib2.ProxyHandler , get the proxy off from registry , since I haven't explicitly set the proxy ?

但是你明確設置代理{}。由於文檔說:

To disable autodetected proxy pass an empty dictionary.

取而代之的是:

proxy_support = urllib2.ProxyHandler({}) 

你需要這樣做:

proxy_support = urllib2.ProxyHandler() 
+0

有道理,但是,當我這樣做,它'的urllib2來了.HTTPError:HTTP錯誤407:需要代理身份驗證如何克服該問題? – misguided

+0

@misguided:這意味着您的代理需要某種身份驗證。無論是基本的,摘要還是NTLM,我都不知道。但是,如果您只需在文檔中向下滾動幾行,就可以看到用於這些文檔的類,並帶有指向「HTTPPasswordMgr」的鏈接。 [示例](http://docs.python.org/2/library/urllib2.html#examples)演示瞭如何創建和使用代理身份驗證處理程序。 – abarnert