2013-02-18 89 views
2

我试图通过代理使用urllib2;然而,在尝试使用urllib2来通过我的验证细节的每一个变化之后,我要么获得永久挂起并且什么都不返回的请求,要么我得到407 Errors。我可以使用连接到prox-pac并重定向的浏览器连接到网络。然而,我似乎无法通过命令行curl,wget,urllib2等做任何事情,即使我使用prox-pac重定向到的代理。我尝试使用urllib2将代理设置为来自pac文件的所有代理,但其中没有一个可以工作。通过代理使用urllib2

我现在的剧本是这样的:

import urllib2 as url 

proxy = url.ProxyHandler({'http': 'username:[email protected]:8080'}) 
auth = url.HTTPBasicAuthHandler() 
opener = url.build_opener(proxy, auth, url.HTTPHandler) 
url.install_opener(opener) 
url.urlopen("http://www.google.com/") 

会抛出HTTP Error 407: Proxy Authentication Required,我也试过:

import urllib2 as url 

handlePass = url.HTTPPasswordMgrWithDefaultRealm() 
handlePass.add_password(None, "http://my.proxy:8080", "username", "password") 
auth_handler = url.HTTPBasicAuthHandler(handlePass) 
opener = url.build_opener(auth_handler) 
url.install_opener(opener) 
url.urlopen("http://www.google.com") 

它挂像curlwget超时。

我需要做些什么来诊断问题?我怎么可能通过我的浏览器进行连接,而不是通过同一台计算机上的命令行进行连接,而使用看起来相同的代理和凭证?

可能与路由器有关吗?如果是这样,请问如何区分浏览器HTTP请求和命令行HTTP请求?

回答

3

像这样的沮丧是什么驱使我使用Requests。如果你正在用urllib2做大量的工作,你真的应该检查出来。例如,你想使用的要求做什么,你可以写:

import requests 
from requests.auth import HTTPProxyAuth 

proxy = {'http': 'http://my.proxy:8080'} 
auth = HTTPProxyAuth('username', 'password') 
r = requests.get('http://wwww.google.com/', proxies=proxy, auth=auth) 
print r.text 

或者你可以将它包装在一个Session对象,每个请求将自动使用代理信息(加上它将存储&处理Cookie自动!):

s = requests.Session(proxies=proxy, auth=auth) 
r = s.get('http://www.google.com/') 
print r.text