urllib2.urlopen始终报出“No such file or directory”错误


在修改之前用python做的一个词典工具时出现莫名其妙的错误( python代码链接 ),排查发现可能是开放API的问题。
这是我用来获取词典数据的url:
http://fanyi.youdao.com/openapi.do?keyfrom=mypydict&doctype=json&q=test&version=1.1&key=27855339&type=data
在浏览器中打开可以看到正确的数据,但是我的程序里,或者使用curl获取数据都会出错。在程序中添加User-Agent也没有效果。
请问这是怎么一回事?
===update===
用python获取数据的样例代码如下


 import urllib, urllib2
url = 'http://fanyi.youdao.com/openapi.do'
params = {'keyfrom': 'mypydict', 
'doctype': 'json', 
'q': 'test', 
'version': 1.1, 
'key': '27855339', 
'type': 'data'}
data = urllib.urlencode(params)
req = urllib2.Request(url, data)
fd = urllib2.urlopen(req)

最后一行报错
URLError: <urlopen error [Errno 2] No such file or directory>
===update===
事情变得有些灵异,有两位说他们跑我的程序没问题,但我自己跑却报错。我发现不管url的值是什么都会报错,连 urllib2.urlopen('http://www.python.org') 这样简单的程序也会出错。 完整的出错信息如下:


 URLError                                  Traceback (most recent call last)
<ipython-input-23-6182f2d9962b> in <module>()
----> 1 urllib2.urlopen(url)

/usr/lib/python2.7/urllib2.pyc in urlopen(url, data, timeout)
    125     if _opener is None:
    126         _opener = build_opener()
--> 127     return _opener.open(url, data, timeout)
    128 
    129 def install_opener(opener):

/usr/lib/python2.7/urllib2.pyc in open(self, fullurl, data, timeout)
    402             req = meth(req)
    403 
--> 404         response = self._open(req, data)
    405 
    406         # post-process response

/usr/lib/python2.7/urllib2.pyc in _open(self, req, data)
    420         protocol = req.get_type()
    421         result = self._call_chain(self.handle_open, protocol, protocol +
--> 422                                   '_open', req)
    423         if result:
    424             return result

/usr/lib/python2.7/urllib2.pyc in _call_chain(self, chain, kind, meth_name, *args)
    380             func = getattr(handler, meth_name)
    381 
--> 382             result = func(*args)
    383             if result is not None:
    384                 return result

/usr/lib/python2.7/urllib2.pyc in http_open(self, req)
   1212 
   1213     def http_open(self, req):
-> 1214         return self.do_open(httplib.HTTPConnection, req)
   1215 
   1216     http_request = AbstractHTTPHandler.do_request_

/usr/lib/python2.7/urllib2.pyc in do_open(self, http_class, req)
   1182         except socket.error, err: # XXX what error?
   1183             h.close()
-> 1184             raise URLError(err)
   1185         else:
   1186             try:

URLError: <urlopen error [Errno 2] No such file or directory>

我重装了python也还是没用,烦请高手指点。

urllib2 python

堕落的行者 10 years, 11 months ago

 curl http://fanyi.youdao.com/openapi.do -d keyfrom=mypydict -d doctype=json -d q=test -d version=1.1 -d key=27855339 -d type=data

阿婆你太给力了 answered 10 years, 11 months ago

Your Answer