Python和代理 - urllib2.URLError:<urlopen error =“”[errno =“”110] =“”connection =“”timed =“”out =“”> </urlopen>

时间:2013-05-27 14:42:11

标签: python urllib2

我试图google并在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>

我也尝试使用requests库,并得到了同样的错误。

# 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连接设置代理?我该如何修改我的测试脚本?

1 个答案:

答案 0 :(得分:4)

问题出在关闭端口。 在技​​术支持打开我需要的端口之前,我不得不购买专用的IP。

现在我的脚本运行正常。

结论:当您使用共享主机时,大多数端口可能已关闭,您必须联系技术支持人员才能打开端口。

相关问题