このスクリプトを実行して、AlchemyAPI の呼び出しで取得した JSON オブジェクトの内容を出力しようとしていますが、何らかの理由で、ユーザーから URL を受け取った後にプログラムが停止します。Ctrl-C を使用して強制的に閉じると、次のエラーが表示されます。
Traceback (most recent call last):
File "test2.py", line 18, in <module>
json = urllib2.urlopen(url).read()
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 1207, in http_open
return self.do_open(httplib.HTTPConnection, req)
File "/usr/lib/python2.7/urllib2.py", line 1174, in do_open
h.request(req.get_method(), req.get_selector(), req.data, headers)
File "/usr/lib/python2.7/httplib.py", line 958, in request
self._send_request(method, url, body, headers)
File "/usr/lib/python2.7/httplib.py", line 992, in _send_request
self.endheaders(body)
File "/usr/lib/python2.7/httplib.py", line 954, in endheaders
self._send_output(message_body)
File "/usr/lib/python2.7/httplib.py", line 814, in _send_output
self.send(msg)
File "/usr/lib/python2.7/httplib.py", line 776, in send
self.connect()
File "/usr/lib/python2.7/httplib.py", line 757, in connect
self.timeout, self.source_address)
File "/usr/lib/python2.7/socket.py", line 562, in create_connection
sock.connect(sa)
File "/usr/lib/python2.7/socket.py", line 224, in meth
return getattr(self._sock,name)(*args)
これは私が実行しようとしているスクリプトです:
from alchemyapi import AlchemyAPI
from encodings import hex_codec
from encodings import ascii
import httplib,urllib2
import json
import sys
alchemyapi = AlchemyAPI()
prompt = "> "
api_key = "something"
url = raw_input(prompt)
try:
#Accessing Alchemy API to get the relevance
url = "http://access.alchemyapi.com/calls/url/URLGetRankedKeywords?apikey=%s&url=%s&outputMode=json" % (api_key,url)
# sample url: http://access.alchemyapi.com/calls/url/URLGetRankedKeywords?apikey=83da2d0deaef076648b28972905d2f8c1f5e3c0f&url=http://www.google.com&outputMode=json
json = urllib2.urlopen(url).read()
#Parsing the json payload MUST TO THIS TO CONVERT INTO JSON OBJECT
the_data = eval(json)
#Retrieving relevance from the payload. SELECT THE DATA THAT YOU NEED USING THE TREE
print the_data ['keywords'][0]['relevance']
print the_data ['language']
except urllib2.URLError, e:
if hasattr(e, 'reason'):
print 'We failed to reach a server.\r'
print 'Reason: ', e.reason
elif hasattr(e, 'code'):
print 'Sorry! Looks like Klout doesn\'t have info on that soldier!\r'
print 'Error code: ', e.code
〜
エラーが という行にあると確信していますが、json = urllib2.urlopen(url).read()
なぜそれが起こっているのかわかりません。この問題を解決するにはどうすればよいですか?