Urllib2似乎忽略了代理设置

时间:2015-03-25 19:50:29

标签: python proxy urllib2

我支持代理,并希望使用urllib2访问外部网站。如果我在我的环境中设置代理,我可以访问外部站点。当我在urllib2中设置代理时,它似乎被忽略,访问失败。

我正在使用的代码是:

import urllib2
import os
import sys

uri = "https://www.python.org"

http_proxy_server = "192.168.12.20"
http_proxy_port = "8082"
http_proxy = "http://%s:%s" % (http_proxy_server, http_proxy_port)

def open_url_no_proxy():
    sys.stdout.write('Proxy (none): ')
    proxy_handler = urllib2.ProxyHandler({})
    opener = urllib2.build_opener(proxy_handler)
    try:
        opener.open(uri)
        sys.stdout.write('PASS\n')
    except urllib2.URLError:
        sys.stdout.write('FAIL\n')

def open_url_system_proxy():
    sys.stdout.write('Proxy (system): ')
    opener = urllib2.build_opener()
    try:
        opener.open(uri)
        sys.stdout.write('PASS\n')
    except urllib2.URLError:
        sys.stdout.write('FAIL\n')

def open_url_installed_opener():
    sys.stdout.write('Proxy (installed): ')
    proxy_handler = urllib2.ProxyHandler({"http": http_proxy})
    opener = urllib2.build_opener(proxy_handler)
    try:
        opener.open(uri)
        sys.stdout.write('PASS\n')
    except urllib2.URLError:
        sys.stdout.write('FAIL\n')

if __name__ == "__main__":
    os.environ['no_proxy'] = 'localhost,127.0.0.1'
    os.environ['NO_PROXY'] = 'localhost,127.0.0.1'
    os.environ['http_proxy'] = http_proxy
    os.environ['HTTP_PROXY'] = http_proxy
    open_url_system_proxy()
    open_url_no_proxy()
    open_url_system_proxy()
    open_url_installed_opener()
    open_url_system_proxy()

我的系统响应是:

$ python proxytest2.py 
Proxy (system): PASS
Proxy (none): FAIL
Proxy (system): PASS
Proxy (installed): FAIL
Proxy (system): PASS

我做错了什么?

1 个答案:

答案 0 :(得分:2)

您在下面的行中只设置了HTTP代理,但您正在访问HTTPS站点:

 proxy_handler = urllib2.ProxyHandler({"http": http_proxy})

您需要将其修改为

 proxy_handler = urllib2.ProxyHandler({"http": http_proxy, "https": http_proxy})