#!/use/bin/env python #-*- coding: utf-8 -*- '''urllib2_proxy_handler.py @author: Zhang Kai @note: Example for using urllib2.urlopen() with a proxy server requiring authentication. @date: 30/07/2013 ''' import urllib2 URI = "http://www.baidu.com" HTTP_PROXY_SERVER = "135.33.33.33" HTTP_PROXY_PORT = "80" HTTP_PROXY_REALM = HTTP_PROXY_SERVER #Worked in my(limited) testing environment. HTTP_PROXY_USER = "apprentice" HTTP_PROXY_PASSWD = "xxx" #Next Line = "http://username:password@someproxyserver.com:3128" HTTP_PROXY_FULL_AUTH_STRING = "http://%s:%s@%s:%s" %(HTTP_PROXY_USER, HTTP_PROXY_PASSWD, HTTP_PROXY_SERVER, HTTP_PROXY_PORT) def open_url_no_proxy(): urllib2.urlopen(URI) print "Apparent success without proxy server!" def open_url_installed_opener(): proxy_handler = urllib2.ProxyHandler({"http":HTTP_PROXY_FULL_AUTH_STRING}) opener = urllib2.build_opener(proxy_handler) urllib2.install_opener(opener) urllib2.urlopen(URI) print "Apparent success through proxy server!" if __name__ == "__main__": try: open_url_no_proxy() except Exception: open_url_installed_opener()
輸出: python