Python NameError: 名称 'urlopen' 未定义
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17330910/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
NameError: name 'urlopen' is not defined
提问by apples723
ok this is my last question so i finally found an api that prints good and that works but my problem is im getting errors if someone could look at this for me and tell me whats wrong that would be great
好的,这是我的最后一个问题,所以我终于找到了一个打印良好且有效的 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()
and here is the error
这是错误
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
回答by Elazar
You did not import the name urlopen.
您没有导入 name urlopen。
Since you are using python3, you'll need urllib.request:
由于您使用的是python3,因此您需要urllib.request:
from urllib.request import urlopen
req = urlopen(...)
or explicitly referring to the requestmodule
或明确引用request模块
import urllib.request
req = request.urlopen(...)
in python2 this would be
在python2中这将是
from urllib import urlopen
or use urllib.urlopen.
或使用urllib.urlopen.
Note:
You are also overriding the name jsonwhich is not a good idea.
注意:您还覆盖了名称json,这不是一个好主意。
回答by AMADANON Inc.
Python does not know that the urlopenyou refer to (line 4) is the urlopenfrom urllib. You have two options:
Python 不知道urlopen您所指的(第 4 行)是urlopenfrom urllib。您有两个选择:
- Tell Python that it is - replace
urlopenwithurllib.urlopen - Tell Python that ALL references to
urlopenare the one fromurllib: replace the lineimport urllibtofrom urllib import urlopen
- 告诉 Python 它是 - 替换
urlopen为urllib.urlopen - 告诉 Python 对的所有引用
urlopen都是来自urllib:将行替换import urllib为from urllib import urlopen
回答by msturdy
it should be:
它应该是:
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()
You didn't specifically import the urlopen()method from the urlliblibrary.
您没有专门urlopen()从urllib库中导入该方法。

