python - urllib2.urlopen始终报出“No such file or directory”错误
迷茫
迷茫 2017-04-17 11:25:11
0
1
954

在修改之前用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也还是没用,烦请高手指点。

迷茫
迷茫

业精于勤,荒于嬉;行成于思,毁于随。

Antworte allen(1)
洪涛
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
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage