Python的urllib2无法连接到任何东西

时间:2014-09-10 16:54:40

标签: python connection urllib2 urlopen

我可以ping并且也可以在同一台机器的浏览器中看到google.com,但是当我尝试使用urllib2.urlopen(url)时它会失败。为什么呢?

tmac:~ torobinson$ ping google.com
PING google.com (4.35.2.172): 56 data bytes
64 bytes from 4.35.2.172: icmp_seq=0 ttl=57 time=2.536 ms
64 bytes from 4.35.2.172: icmp_seq=1 ttl=57 time=1.447 ms
64 bytes from 4.35.2.172: icmp_seq=2 ttl=57 time=1.415 ms
^C
--- google.com ping statistics ---
3 packets transmitted, 3 packets received, 0.0% packet loss
round-trip min/avg/max/stddev = 1.415/1.799/2.536/0.521 ms
tmac:~ torobinson$ python
Python 2.7.3 (v2.7.3:70274d53c1dd, Apr  9 2012, 20:52:43) 
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import urllib2
>>> urllib2.urlopen('http://google.com')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 126, in urlopen
return _opener.open(url, data, timeout)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 400, in open
response = self._open(req, data)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 418, in _open
'_open', req)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 378, in _call_chain
result = func(*args)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 1207, in http_open
return self.do_open(httplib.HTTPConnection, req)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 1177, in do_open
raise URLError(err)
urllib2.URLError: <urlopen error [Errno 61] Connection refused>

什么可能导致这种情况?

编辑:abarnert让我走上了正确的道路。安装ProxyHandler后工作:

    proxy_support = urllib2.ProxyHandler({})
    opener = urllib2.build_opener(proxy_support)
    urllib2.install_opener(opener)
    response = urllib2.urlopen("http://google.com")
    print response.read()

0 个答案:

没有答案