1

我在 Windows XP PC 上使用带有 VitualBox 的 Ubuntu 12。我正在使用代理访问互联网。我可以使用 Firefox 浏览这些网站,并查看以下脚本:

import urllib2
import json

proxy = urllib2.ProxyHandler({'http': 'http://my-proxy-server:80'})
auth = urllib2.HTTPBasicAuthHandler()
opener = urllib2.build_opener(proxy, auth, urllib2.HTTPHandler)
urllib2.install_opener(opener)

#conn = urllib2.urlopen('http://python.org')
return_str = conn.read()
print return_str

上面的代码一切顺利,但对于下面的类似代码不起作用。

import urllib2
import json

proxy = urllib2.ProxyHandler({'http': 'http://my-proxy-server:80'})
auth = urllib2.HTTPBasicAuthHandler()
opener = urllib2.build_opener(proxy, auth, urllib2.HTTPHandler)
urllib2.install_opener(opener)


response = urllib.urlopen('https://api.twitter.com/1.1/search/tweets.json?q=microsoft')
print json.load(response)

错误日志如下。

Traceback (most recent call last):
  File "print.py", line 12, in <module>
    conn = urllib2.urlopen('https://api.twitter.com/1.1/search/tweets.json?q=microsoft')
  File "/usr/lib/python2.7/urllib2.py", line 126, in urlopen
    return _opener.open(url, data, timeout)
  File "/usr/lib/python2.7/urllib2.py", line 400, in open
    response = self._open(req, data)
  File "/usr/lib/python2.7/urllib2.py", line 418, in _open
    '_open', req)
  File "/usr/lib/python2.7/urllib2.py", line 378, in _call_chain
    result = func(*args)
  File "/usr/lib/python2.7/urllib2.py", line 1215, in https_open
    return self.do_open(httplib.HTTPSConnection, req)
  File "/usr/lib/python2.7/urllib2.py", line 1177, in do_open
    raise URLError(err)
urllib2.URLError: <urlopen error [Errno 113] No route to host>

请帮帮我。谢谢。

4

1 回答 1

0

尝试创建一个 https 处理程序,看看是否能解决问题。

更改此行:

proxy = urllib2.ProxyHandler({'http': 'http://my-proxy-server:80'})

proxy = urllib2.ProxyHandler({'https': 'http://my-proxy-server:80'})  

看看这是否有效,因为您尝试访问的 Twitter API 是通过 HTTPS 进行的。

于 2013-07-03T06:51:06.920 回答