【问题标题】:Python and proxy - urllib2.URLError: <urlopen error [Errno 110] Connection timed out>Python 和代理 - urllib2.URLError: <urlopen 错误 [Errno 110] 连接超时>
【发布时间】:2013-05-27 14:42:10
【问题描述】:

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

【问题讨论】:

  • ping www.whatismyip.com 在服务器上?
  • ping: icmp open socket: Operation not permitted
  • 服务器是什么操作系统?在我看来,服务器未配置为以您期望的方式允许 http 请求。您还说“如果我不设置代理,那么程序就可以工作” - 所以....不要设置代理并享受工作程序!??!!?
  • 亲爱的 Vosrsprung!据我所知,操作系统是 Debian。我有理由使用代理,所以你关于“不设置代理”的建议不是很有帮助,也不合适。
  • 我在托管服务提供商的技术支持处开了一张票,他们回答说他们服务器上的大多数端口默认关闭,要打开端口我需要购买专用 IP。

标签: python urllib2


【解决方案1】:

问题出在关闭的端口。 我必须先购买专用 IP,然后技术支持才能打开我需要的端口。

现在我的脚本可以正常工作了。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-13
    • 1970-01-01
    相关资源
    最近更新 更多