6

わかりましたこれは私の最後の質問なので、最終的にうまく印刷できるAPIを見つけましたが、私の問題は、誰かが私のためにこれを見て何が悪いのか教えてくれるとエラーが発生することです。

import urllib
import json

request = urlopen("http://api.exmaple.com/stuff?client_id=someid&client_secret=randomsecret")
response = request.read()
json = json.loads(response)
if json['success']:
     ob = json['response']['ob']
     print ("The current weather in Seattle is %s with a temperature of %d") % (ob['weather'].lower(), ob['tempF'])
else:
     print ("An error occurred: %s") % (json['error']['description'])
request.close()

ここにエラーがあります

Traceback (most recent call last):
File "thing.py", line 4, in <module>
request = urlopen("http://api.exmaple.com/stuff?client_id=someid&client_secret=randomsecret")
NameError: name 'urlopen' is not defined
4

3 に答える 3

23

名前 をインポートしませんでしたurlopen

python3 を使用しているため、以下が必要になりますurllib.request

from urllib.request import urlopen
req = urlopen(...)

requestまたはモジュールを明示的に参照する

import urllib.request
req = request.urlopen(...)

python2 では、これは

from urllib import urlopen

または使用しますurllib.urlopen


注: 名前もオーバーライドしていますが、jsonこれはお勧めできません。

于 2013-06-26T21:38:42.083 に答える
2

urlopenPython は、参照先 (4 行目) がurlopenfromであることを知りませんurllib。次の 2 つのオプションがあります。

  1. それがそうであることをPythonに伝えます - に置き換えurlopenますurllib.urlopen
  2. urlopenへのすべての参照が からのものであることを Python に伝えます: への行をurllib置き換えますimport urllibfrom urllib import urlopen
于 2013-06-26T21:38:52.963 に答える
1

そのはず:

import urllib
import json

request  = urllib.urlopen("http://api.example.com/endpoint?client_id=id&client_secret=secret")
response = request.read()
json = json.loads(response)

if json['success']:
     ob = json['response']['ob']
     print ("The current weather in Seattle is %s with a temperature of %d") % (ob['weather'].lower(), ob['tempF'])

else:
     print ("An error occurred: %s") % (json['error']['description'])

request.close()

ライブラリurlopen()からメソッドを具体的にインポートしませんでした。urllib

于 2013-06-26T21:41:32.053 に答える