我试图谷歌并在stackOverflow上搜索类似的问题,但仍然无法解决我的问题。
我需要我的 python 脚本通过代理执行 http 连接。
下面是我的测试脚本:
import urllib2, urllib
proxy = urllib2.ProxyHandler({'http': 'http://255.255.255.255:3128'})
opener = urllib2.build_opener(proxy, urllib2.HTTPHandler)
urllib2.install_opener(opener)
conn = urllib2.urlopen('http://www.whatismyip.com/')
return_str = conn.read()
webpage = open('webpage.html', 'w')
webpage.write(return_str)
webpage.close()
该脚本在我的本地计算机(Windows 7,Python 2.7.3)上运行良好,但是当我尝试在服务器上运行它时,它给了我以下错误:
Traceback (most recent call last):
File "proxy_auth.py", line 18, in <module>
conn = urllib2.urlopen('http://www.whatismyip.com/')
File "/home/myusername/python/lib/python2.7/urllib2.py", line 126, in urlopen
return _opener.open(url, data, timeout)
File "/home/myusername/python/lib/python2.7/urllib2.py", line 400, in open
response = self._open(req, data)
File "/home/myusername/python/lib/python2.7/urllib2.py", line 418, in _open
'_open', req)
File "/home/myusername/python/lib/python2.7/urllib2.py", line 378, in _call_chai n
result = func(*args)
File "/home/myusername/python/lib/python2.7/urllib2.py", line 1207, in http_open
return self.do_open(httplib.HTTPConnection, req)
File "/home/myusername/python/lib/python2.7/urllib2.py", line 1177, in do_open
raise URLError(err)
urllib2.URLError: <urlopen error [Errno 110] Connection timed out>
我也尝试使用请求库,并得到了同样的错误。
# testing request library
r = requests.get('http://www.whatismyip.com/', proxies={'http':'http://255.255.255.255:3128'})
如果我不设置代理,那么程序可以正常工作。
# this works fine
conn = urllib2.urlopen('http://www.whatismyip.com/')
我认为问题在于,在我的共享主机帐户上,无法为代理设置环境变量......或类似的东西。
是否有任何解决方法或替代方法可以让我为 http 连接设置代理?我应该如何修改我的测试脚本?