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

Python 不知道urlopen您所指的(第 4 行)是urlopenfrom urllib。你有两个选择:

  1. 告诉 Python 它是 - 替换urlopenurllib.urlopen
  2. 告诉 Python 所有对urlopen的引用都是 from 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 回答