2008-08-29 26 views

回答

56

這個工作對我來說:

import urllib2 

proxy = urllib2.ProxyHandler({'http': 'http:// 
username:[email protected]:proxyport'}) 
auth = urllib2.HTTPBasicAuthHandler() 
opener = urllib2.build_opener(proxy, auth, urllib2.HTTPHandler) 
urllib2.install_opener(opener) 

conn = urllib2.urlopen('http://python.org') 
return_str = conn.read() 
+0

默認情況下添加urllib2.HTTPHandler(請參閱urllib2 doc)。在建造開罐器時加入它似乎是多餘的。 – HongboZhu 2013-09-21 20:46:40

+0

如果不涉及身份驗證,爲什麼使用urllib2.HTTPBasicAuthHandler()? – HongboZhu 2013-09-21 23:25:38

9

的經歷需要身份驗證的代理使用urllib2建立一個定製URL開啓,然後使用該做所有你想通過這些請求的最佳方式代理人。特別要注意的是,您可能不希望將代理密碼嵌入到url或python源代碼中(除非它只是一個快速破解)。

import urllib2 

def get_proxy_opener(proxyurl, proxyuser, proxypass, proxyscheme="http"): 
    password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm() 
    password_mgr.add_password(None, proxyurl, proxyuser, proxypass) 

    proxy_handler = urllib2.ProxyHandler({proxyscheme: proxyurl}) 
    proxy_auth_handler = urllib2.ProxyBasicAuthHandler(password_mgr) 

    return urllib2.build_opener(proxy_handler, proxy_auth_handler) 

if __name__ == "__main__": 
    import sys 
    if len(sys.argv) > 4: 
     url_opener = get_proxy_opener(*sys.argv[1:4]) 
     for url in sys.argv[4:]: 
      print url_opener.open(url).headers 
    else: 
     print "Usage:", sys.argv[0], "proxy user pass fetchurls..." 

在更復雜的程序,可以單獨這些組件進行適當的(例如,僅可使用應用程序的生命週期一個密碼管理器)。 python文檔有more examples on how to do complex things with urllib2,你可能也會覺得有用。

3

或者,如果你想安裝它,所以它總是與urllib2.urlopen使用(這樣你就不會需要參考保持到了揭幕戰左右):

import urllib2 
url = 'www.proxyurl.com' 
username = 'user' 
password = 'pass' 
password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm() 
# None, with the "WithDefaultRealm" password manager means 
# that the user/pass will be used for any realm (where 
# there isn't a more specific match). 
password_mgr.add_password(None, url, username, password) 
auth_handler = urllib2.HTTPBasicAuthHandler(password_mgr) 
opener = urllib2.build_opener(auth_handler) 
urllib2.install_opener(opener) 
print urllib2.urlopen("http://www.example.com/folder/page.html").read() 
13

設置環境VAR命名HTTP_PROXY這樣的:HTTP://用戶名:密碼@ proxy_url:端口

1

這裏是方法使用的urllib

import urllib.request 

# set up authentication info 
authinfo = urllib.request.HTTPBasicAuthHandler() 
proxy_support = urllib.request.ProxyHandler({"http" : "http://ahad-haam:3128"}) 

# build a new opener that adds authentication and caching FTP handlers 
opener = urllib.request.build_opener(proxy_support, authinfo, 
            urllib.request.CacheFTPHandler) 

# install it 
urllib.request.install_opener(opener) 

f = urllib.request.urlopen('http://www.python.org/') 
""" 
0

使用此:

import requests 

proxies = {"http":"http://username:[email protected]_ip:proxy_port"} 

r = requests.get("http://www.example.com/", proxies=proxies) 

print r.content 

我認爲這是比使用urllib簡單得多。我不明白爲什麼人們喜歡使用urllib這麼多。

相關問題